instance method
change
Ruby on Rails 7.2.3
Since v3.0.20Signature
change(options)
Returns a new DateTime where one or more of the elements have been changed according to the options parameter. The time options (:hour, :min, :sec) reset cascadingly, so if only the hour is passed, then minute and sec is set to 0. If the hour and minute is passed, then sec is set to 0. The options parameter takes a hash with any of these keys: :year, :month, :day, :hour, :min, :sec, :offset, :start.
DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0) DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0) DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
Parameters
-
optionsreq
Source
# File activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 51
def change(options)
if new_nsec = options[:nsec]
raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
new_fraction = Rational(new_nsec, 1000000000)
else
new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
new_fraction = Rational(new_usec, 1000000)
end
raise ArgumentError, "argument out of range" if new_fraction >= 1
::DateTime.civil(
options.fetch(:year, year),
options.fetch(:month, month),
options.fetch(:day, day),
options.fetch(:hour, hour),
options.fetch(:min, options[:hour] ? 0 : min),
options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) + new_fraction,
options.fetch(:offset, offset),
options.fetch(:start, start)
)
end
Defined in activesupport/lib/active_support/core_ext/date_time/calculations.rb line 51
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in DateTime