Having recently spun myself in circles looking at these options, I thought I’d spin up a guide on Ruby’s three timekeeping classes.
What are Date, Time, and DateTime?
All three are Ruby classes used for working with time. Time is built-in to Ruby; Date and DateTime come from the standard library date.
#=> 2020-12-31 06:23:24 +0000require 'date'Date.today
#=> #<Date: 2020-12-31 ((2459215j,0s,0n),+0s,2299161j)>DateTime.now
#=> #<DateTime: 2020-12-31T06:23:24+00:00
They can also be created as specific other times. For example, for Time:
#=> 2030-01-01 00:00:00 +0000Time.new(2030, 6, 6, 6, 4, 20, "+00:00")
#=> 2030-06-06 06:04:20 +0000Time.at(4500000000)
#=> 2112-08-07 08:00:00 +0000
Which one should I use?
DateTime is considered deprecated. It only still exists to be backwards-compatible.
As of Ruby 3 (released December 24th, 2020, as is Ruby tradition), DateTime only exists for backwards-compatibility. The date library docs recommend you just use Time instead. (I’m pretty sure this was essentially true from 2.0 forward, but now it’s formally true.)
If you’re someone who googles around for answers (which you are, that’s why you’re here), keep this in mind! A lot of old articles are now misleading.
This simplifies our question by a lot. The biggest difference between Date and Time is that Date is concerned with days and above; if you care at all about hours, minutes, seconds and below, or think you might care about them in the future, you have to use Time. Date can’t handle any of that.
On the other hand, here are some things Date can do better than Time:
- Handle history. Date has support for historical calendar reforms. If you use Time to represent and work with dates from hundreds of years ago, you’ll be faking it and they won’t match up with historical records, because we’ve changed our calendars and Time is basically just a number of seconds since or before January 1st, 1970 and nothing more. Date even differentiates between when different polities adopted calendar reforms.
- Be configured to accept dates in different formats. If you’re expecting to import date information from text sources, especially varied sources, Date will have an easier time parsing things. (Look into its parse and strptime methods for this.)
- Make customized calendar decisions. Both Time and Date can tell you it’s the second day of the week — but Date can be told in advance that you count your weeks starting on Monday, not Sunday.
Let me know if you can think of any other important use-cases.