Working with Dates and Times (date)

Core Ruby has a Time class, but we will encounter a lot of situations where we also need to work with dates, or combinations of dates and times. Ruby’s date standard library gives us Date and DateTime, and extends Time with conversion methods for each of them. This library comes packed with a powerful parser that can handle all sorts of date formats, and a solid date formatting engine to output data based on a template. Here are just a couple of trivial examples to give you a sense of its flexibility:

>> Date.strptime("12/08/1985","%m/%d/%Y").strftime("%Y-%m-%d")
=> "1985-12-08"
>> Date.strptime("1985-12-08","%Y-%m-%d").strftime("%m/%d/%Y")
=> "12/08/1985"
>> Date.strptime("December 8, 1985","%b%e, %Y").strftime("%m/%d/%Y")
=> "12/08/1985"

Date objects can also be queried for all sorts of information, as well as manipulated to produce new days:

>> date = Date.today
=> #<Date: 2009-02-09 (4909743/2,0,2299161)>
>> date + 1
=> #<Date: 2009-02-10 (4909745/2,0,2299161)>
>> date << 1
=> #<Date: 2009-01-09 (4909681/2,0,2299161)>
>> date >> 1
=> #<Date: 2009-03-09 (4909799/2,0,2299161)>
>> date.year
=> 2009
>> date.month
=> 2
>> date.day
=> 9
>> date.wday
=> 1
>> date + 36
=> #<Date: 2009-03-17 (4909815/2,0,2299161)>

Here we’ve just scratched the surface, but in the interest of keeping a quick pace, we’ll dive right into an example. So far, we’ve been looking at Date, but now we’re going to work with DateTime. The two are basically the same, except that the ...

Get Ruby Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.