Time, DateTime, and TimeWithZone in Rails
Start dealing with time in Rails—which is unavoidable in any real application—and you’ll quickly run into the same first question: Rails gives you three different classes to represent time—Time, DateTime, and ActiveSupport::TimeWithZone. What’s actually the difference between them?
Let’s get the basics out of the way first.
Time vs. DateTime
Before TimeWithZone enters the picture, Time and DateTime—both shipped with Ruby out of the box—are probably the first time classes you touch. Like me, you’ve probably wondered how they differ and which one you’re supposed to use.
In terms of where they live, Time is part of Ruby’s core library and is available without requiring anything. DateTime is a subclass of Date in the standard library (std-lib), so using it outside Rails requires an explicit require 'date'.
If you stumble across older articles, you might read that “Time is a thin wrapper around POSIX time and can only represent timestamps after 1970-01-01 00:00:00 +00:00.” That hasn’t been true since Ruby 1.9.2:
Since Ruby 1.9.2, Time implementation uses a signed 63 bit integer, Bignum or Rational. The integer is a number of nanoseconds since the Epoch which can represent 1823-11-12 to 2116-02-20. When Bignum or Rational is used (before 1823, after 2116, under nanosecond), Time works slower as when integer is used.
In day-to-day use, Time and DateTime behave almost identically. Both handle years, months, days, hours, minutes, seconds, weekdays, and time offsets—covering nearly every common use case. Where DateTime shines is when you need to account for historical calendar reforms. Here is an example straight from the Ruby docs; if reading it leaves you both shocked and completely baffled, don’t overthink it—it just means you have no need for DateTime.
shakespeare = DateTime.iso8601('1616-04-23', Date::ENGLAND)
#=> Tue, 23 Apr 1616 00:00:00 +0000
cervantes = DateTime.iso8601('1616-04-23', Date::ITALY)
#=> Sat, 23 Apr 1616 00:00:00 +0000DateTime vs. TimeWithZone
ActiveSupport::TimeWithZone (hereafter TimeWithZone) is the default class ActiveRecord uses for datetime database columns, designed to make time zones painless in Rails. While Ruby’s built-in Time and DateTime also store offset information, they rely on the system’s ENV['TZ'] environment variable and only switch between local time and GMT/UTC1—which is fine for a single-locale app, but falls short once you’re building an internationalized app that has to juggle multiple time zones.
Most of the time you might not even notice whether you’re holding a TimeWithZone or a DateTime. After Rails’ ActiveSupport extensions, the two share nearly identical instance methods: both can add and subtract durations, and both convert cleanly to one another. Assuming you never have to care which concrete class you’re dealing with, however, is a bit naive.
Both classes let you add and subtract durations, but there is a subtle catch: when calculating variable-length durations (days, months, years, etc.), DateTime completely ignores Daylight Saving Time (DST). Adding a duration to a DateTime across a DST boundary leaves its clock time and UTC offset (%T %z) unchanged. By contrast, when a TimeWithZone instance is in a time zone that observes DST, crossing a DST boundary adjusts the UTC offset accordingly so the wall-clock time matches human intuition.
If your application cares about exact duration math, this distinction matters—and it’s remarkably easy to get burned without realizing it. As mentioned earlier, ActiveRecord maps datetime columns to TimeWithZone. Suppose we have a periods table storing start_time and end_time, and for a given record those timestamps straddle a DST transition in the app’s configured time zone. Because DateTime and TimeWithZone do duration math differently, the value calculated in memory before saving won’t match the value recalculated after reading the record back from the database:
start_time = DateTime.current
end_time = start_time + 1.month
Period.create!(start_time: start_time, end_time: end_time)
period = Period.last
period.end_time == period.start_time + 1.month # => not sure!There are two ways to avoid this trap:
- Avoid variable-length calendar durations like days and months when exact spans matter; use fixed durations (hours, minutes, seconds) instead. (Recommended)
- Do all math in a single time zone with a single type—for instance, convert to a UTC
DateTimebefore calculating, and only convert back to the target time zone for display.
ENV[‘TZ’] vs. config.time_zone
In short, Time.now and DateTime.now use the system time zone from ENV['TZ'], whereas TimeWithZone values loaded from the database—along with ActiveSupport’s Time.current and DateTime.current—use the application time zone configured via config.time_zone.
Normally, even if the two time zones differ, they represent the exact same instant in time and compare equal once converted to UTC. Still, mixing the two can produce baffling bugs. Here is a real bug I ran into caused by a mismatch between the system and app time zones. Suppose the current time is 2018-03-01 10:00:00 +0800, the system time zone is Shanghai (+0800), the Rails app time zone is Pacific Time (-0800), and we’re using the same periods table from earlier:
start_time = DateTime.now # 2018-03-01 10:00:00 +0800
end_time = start_time + 2.years # 2020-03-01 10:00:00 +0800
Period.create!(start_time: start_time, end_time: end_time)
period = Period.last
period.start_time.to_datetime + 2.years == period.end_time.to_datetime # => false, 1 day differenceIf I tell you this bug only happens once every four years, you can probably guess where this is going.
The root cause is almost comically simple. In Shanghai time (+0800), March 1, 2018 plus 2 years is March 1, 2020. Once saved to the database and read back, however, start_time is loaded in the app’s time zone (-0800), and calling .to_datetime preserves that -0800 offset. In -0800, the date shifts back from March 1, 2018 to February 28, 2018—which is still the exact same instant in time. But when you add 2.years to February 28, 2018, you land on February 28, 2020. Because 2020 is a leap year, there is a February 29 sitting between February 28 and March 1 that didn’t exist in 2018—and that’s where the one-day gap comes from.
The fix is the same one mentioned earlier: if you need strict, predictable time math, stay away from calendar-relative durations like days, months, and years. And if you must use them, normalize everything to UTC before doing the math and convert to local time zones only at the display layer.
Footnotes
-
GMT (Greenwich Mean Time) and UTC (Coordinated Universal Time) are interchangeable for most practical purposes, and Ruby’s
Time/DateTimetreat them as such. ↩
