HowTo: Date operations
October 10, 2008 Leave a comment
I’m just going to copy and paste the code from this site.
Basically, time and date manipulations are easy as long as the operations involved are additions and subtractions. Quoted from the link above:
Not every arithmetic operation makes sense for dates: you could “multiply two dates” by multiplying the underlying numbers, but that would have no meaning in terms of real time, so Ruby doesn’t define those operators.
Remember:
- Time has a unit of 1 secondrequire ‘date’
y2k = Time.gm(2000, 1, 1) # => Sat Jan 01 00:00:00 UTC 2000
y2k + 1 # => Sat Jan 01 00:00:01 UTC 2000
y2k – 1 # => Fri Dec 31 23:59:59 UTC 1999
y2k + (60 * 60 * 24 * 365) # => Sun Dec 31 00:00:00 UTC 2000y2k_dt = DateTime.new(2000, 1, 1)
(y2k_dt + 1).to_s # => “2000-01-02T00:00:00Z”
(y2k_dt – 1).to_s # => “1999-12-31T00:00:00Z”
(y2k_dt + 0.5).to_s # => “2000-01-01T12:00:00Z”
(y2k_dt + 365).to_s # => “2000-12-31T00:00:00Z” - While DateTime and Date have a unit of 1 dayday_one = Time.gm(1999, 12, 31)
day_two = Time.gm(2000, 1, 1)
day_two – day_one # => 86400.0
day_one – day_two # => -86400.0day_one = DateTime.new(1999, 12, 31)
day_two = DateTime.new(2000, 1, 1)
day_two – day_one # => Rational(1, 1)
day_one – day_two # => Rational(-1, 1)
Printing dates on our views is done by using the method strftime.
d = Date.today # 2008-08-12
d.strftime(‘%b %d, %Y’) # will print August 12, 2008
The following are the format codes. For reference, refer to this site.
| Format | Meaning |
| %a | The abbreviated weekday name (“Sun’’) |
| %A | The full weekday name (“Sunday’’) |
| %b | The abbreviated month name (“Jan’’) |
| %B | The full month name (“January’’) |
| %c | The preferred local date and time representation |
| %d | Day of the month (01..31) |
| %H | Hour of the day, 24-hour clock (00..23) |
| %I | Hour of the day, 12-hour clock (01..12) |
| %j | Day of the year (001..366) |
| %m | Month of the year (01..12) |
| %M | Minute of the hour (00..59) |
| %p | Meridian indicator (“AM’’ or “PM’’) |
| %S | Second of the minute (00..60) |
| %U | Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) |
| %W | Week number of the current year, starting with the first Monday as the first day of the first week (00..53) |
| %w | Day of the week (Sunday is 0, 0..6) |
| %x | Preferred representation for the date alone, no time |
| %X | Preferred representation for the time alone, no date |
| %y | Year without a century (00..99) |
| %Y | Year with century |
| %Z | Time zone name |
| %% | Literal “%’’ character |