DST and Timestamps
How daylight saving time affects timestamps and software. Learn about the tricky edge cases, ambiguous times, and best practices for DST handling.
Concept
DST transition
Detailed Explanation
Daylight Saving Time (DST) is the practice of advancing clocks by one hour during warmer months to extend evening daylight. For developers, DST creates some of the most subtle and frustrating bugs in software because it makes the relationship between wall-clock time and UTC inconsistent throughout the year.
The two dangerous transitions:
Spring forward: When clocks jump from 2:00 AM to 3:00 AM, the times between 2:00 and 2:59 do not exist. If your system schedules a task for 2:30 AM on a spring-forward day, it will either be skipped or must be shifted.
Fall back: When clocks move from 2:00 AM back to 1:00 AM, the times between 1:00 and 1:59 occur twice. A timestamp of "1:30 AM" is ambiguous — it could refer to either the first or second occurrence.
Spring forward (US, 2nd Sunday of March):
1:59 AM EST → 3:00 AM EDT (2:00-2:59 doesn't exist)
Fall back (US, 1st Sunday of November):
1:59 AM EDT → 1:00 AM EST (1:00-1:59 happens twice)
Why Unix timestamps are immune: Unix timestamps count seconds from epoch in UTC without any DST consideration. The value increases monotonically. DST only affects the conversion between a Unix timestamp and a local wall-clock time. This is another reason to always store timestamps in UTC or as Unix epoch values.
Practical pitfalls:
- Subtracting dates to get "one day" does not always equal 86,400 seconds. On DST transition days, a day can be 23 or 25 hours long.
- Cron jobs scheduled between 2:00-2:59 AM can fire twice on fall-back day or not at all on spring-forward day.
- Duration calculations using local times across DST boundaries produce wrong results.
Best practices:
Always perform date arithmetic in UTC, then convert to local time for display. Use IANA timezone rules (the tzdata or Olson database) rather than hardcoding offsets. Keep your timezone database updated — governments change DST rules frequently (and sometimes with little notice, as Jordan and Chile have done recently).
Use Case
An on-call rotation system must handle DST correctly: a shift scheduled from 1 AM to 5 AM on fall-back night should last 5 hours (not 4), or on-call coverage will have a gap.