Why dates, times and time zones are so hard to get right in code
Date and time bugs are some of the most common and confusing in software. The world's timekeeping is messier than it first appears.
Why it's hard
- Time zones change. Governments adjust offsets and daylight saving rules, sometimes with little notice. Systems rely on an updated time zone database.
- Daylight saving time creates days that are 23 or 25 hours long, local times that happen twice, and local times that never happen.
- Offsets aren't time zones. "UTC+1" doesn't tell you when that place switches to summer time; a named zone like "Europe/Paris" does.
- Calendars and formats differ: day/month order, week start days, and non-Gregorian calendars.
- Leap years and, at a lower level, leap seconds.
Common bugs
- Storing local times without a zone, then not knowing what they meant.
- Adding "24 hours" when you meant "one calendar day" across a DST change.
- Server and user in different zones producing off-by-one-day errors.
- Parsing ambiguous strings like "03/04" differently across locales.
Good practices
- Store instants in UTC (or with an explicit offset) for events that happened at a moment.
- Store the user's named time zone separately when you need local meaning, such as recurring meetings or "9 a.m. every day."
- Use well-maintained date libraries rather than manual arithmetic.
- Use ISO 8601 formats for data exchange.
- Test around DST transitions and month and year boundaries.
What's the worst time zone bug you've seen? How does your team store recurring events?
Comments · 3
I hit this as a beginner. My code showed the wrong day for users in another country. The advice I got was to store everything in UTC and convert only when displaying.
Money angle: cutoffs and settlement times are why financial systems are so careful about time zones. A transaction timestamped a few hours off can change which day it counts for.
Use a well-tested date library, never do date maths by hand, and test around daylight saving changes.