Date and Time
64 | Chapter 2: ActiveSupport and RailTies
Conversions from Numeric core_ext/numeric/time.rb
ActiveSupport adds support methods to theNumericclass to support calculations on dates
and times. Numbers can be added to and subtracted fromTimeobjects; the numbers are
treated as seconds. ActiveSupport’s conversion methods convert numbers to seconds. Both
singular and plural time units are supported.
1 == 1.second
60.seconds == 1.minute
60.minutes == 1.hour
24.hours == 1.day
7.days == 1.week
2.weeks == 1.fortnight
30.days == 1.month
365.25.days == 1.year
Time.now # => Thu Dec 28 13:30:39 CST 2006
Time.now - 3.days # => Mon Dec 25 13:30:39 CST 2006
3.days.ago # => Mon Dec 25 13:30:39 CST 2006
5.hours.from_now # => Thu Dec 28 18:30:39 CST 2006
Time calculations core_ext/time/calculations.rb
- Time.days_in_month(month,year)returns the number of days in the provided month.
Year is optional, but if provided, the function will take leap years into account.
Time.days_in_month(2) # => 28
Time.days_in_month(2, 2003) # => 28
Time.days_in_month(2, 2004) # => 29 - Time#change(options)resets one or more components of the time. Thehour,min,sec,
andusecoptions cascade downward—for example, if the hour but not the minute is
specified, the minute will be set to zero.
t = Time.now
t # => Thu Dec 28 13:39:18 CST 2006
t.change(:min => 31, :sec => 12) # => Thu Dec 28 13:31:12 CST 2006
t.change(:hour => 12) # => Thu Dec 28 12:00:00 CST 2006 - The ago and since methods, formerly operating on Time, now operate on
ActiveSupport::Duration objects, to support exact time values. Methods such as
Fixnum#months andFixnum#year now returnActiveSupport::Duration objects:
Table 2-2. Time formats
Format Example
:default Thu Dec 28 13:12:23 CST 2006
:db 2006-12-28 13:12:23
:time 13:12
:short 28 Dec 13:12
:long December 28, 2006 13:12
:rfc822 Thu, 28 Dec 2006 13:12:23 -0600