DST Pitfalls & Safe Storage Patterns
Daylight Saving Time (DST) is responsible for more billing errors, missed calendar appointments, and database inconsistencies than almost any other time-related concept. Here is how to survive it.
The Golden Rule: Store UTC
ALWAYS STORE UTC
Never store local times in your database unless they are strictly for display and decoupled from actual time (e.g., "Store opens at 09:00"). For events that happen at a specific moment, use Unix Timestamps or UTC ISO Strings.
Pitfall 1: The 23/25 Hour Day
A common mistake is assuming a day always has 24 hours (86,400 seconds). On the day DST starts, a day might have 23 hours. When it ends, it might have 25 hours.
// ❌ Adding 24 hours of seconds
const today = new Date('2024-03-10T00:00:00-05:00'); // DST Start in US
const tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
// Result: 2024-03-11T01:00:00-04:00
// Oops! We wanted midnight, but we got 1 AM because the day was only 23 hours long.// ✅ Using Calendar Math
import { addDays } from 'date-fns';
const today = new Date('2024-03-10T00:00:00-05:00');
const tomorrow = addDays(today, 1);
// Result: 2024-03-11T00:00:00-04:00
// The library understands "Add 1 Day", not "Add 86400 Seconds"Pitfall 2: The Non-Existent Hour
When clocks spring forward (e.g., 2:00 AM becomes 3:00 AM), the time 02:30 AM does not exist in that local timezone. If a user tries to schedule a recurring task for 2:30 AM every day, it will fail on that specific day.
Mitigation: Always validate local inputs against the timezone rules. Libraries like standard Java java.timeor Python pytz often handle this by either throwing an error or automatically adjusting.
Pitfall 3: The Ambiguous Hour
When clocks fall back (e.g., 2:00 AM becomes 1:00 AM), the hour from 1:00 AM to 2:00 AM happens twice. One is in DST, one is not. 1:30 AM is ambiguous without an offset.
Time: 2023-11-05 01:30:00 America/New_York Is this Eastern Daylight Time (-04:00) or Eastern Standard Time (-05:00)? Without the offset, you cannot know. Solution: Always store the offset if you store local time string, OR just store the Unix timestamp (which is unique).
Frequently Asked Questions
Should I store dates in local time?
No. Always store timestamps in UTC or as a Unix timestamp. Only convert to local time when displaying the date to the user.
Does Unix timestamp change during DST?
No. Unix timestamp is a linear count of seconds since the epoch (UTC). It is completely agnostic to timezones and DST.
How do I add 1 day to a date safely?
Do not just add 86400 seconds. Use a calendar-aware library function (like .add(1, "day") in dayjs or .plusDays(1) in Java) which accounts for 23h or 25h days.