Sub topic 6
Daylight Saving Time and Other Calendar Pitfalls
This chapter assumes you know how a Date stores one instant as milliseconds since the epoch. It also assumes you know the difference between local and UTC getters and setters, and how to copy a Date before changing it. Here those tools are applied to the cases where calendar time and elapsed time disagree.
The Core Problem: Days Are Not Always 24 Hours
A time value counts real elapsed milliseconds. A calendar day in a local time zone does not always contain the same number of them. When a zone with daylight saving time (DST) "springs forward," one local day lasts 23 hours. When it "falls back," one local day lasts 25 hours. Any code that assumes 1 day = 86,400,000 ms while working in local time is wrong twice a year in most of North America and Europe.
To get repeatable output, the examples pin the process time zone to America/New_York. In 2024 that zone sprang forward on March 10 at 02:00 and fell back on November 3 at 02:00. Save each snippet as a file and run it with the TZ environment variable, for example TZ=America/New_York node dst.js on macOS or Linux.
// Run with: TZ=America/New_York node dst.js
const mar10 = new Date(2024, 2, 10); // local midnight, EST (UTC-5)
const mar11 = new Date(2024, 2, 11); // local midnight, EDT (UTC-4)
console.log((mar11 - mar10) / 3_600_000); // 23
const nov3 = new Date(2024, 10, 3);
const nov4 = new Date(2024, 10, 4);
console.log((nov4 - nov3) / 3_600_000); // 25Pitfall 1: Adding 24 Hours Instead of One Day
Ask yourself what the user means. "Remind me in 24 hours" is an elapsed duration, so you add milliseconds. "Remind me tomorrow at the same time" is a calendar step, so you change the local date field and let the engine work out the offset.
// Run with: TZ=America/New_York node add-day.js
const start = new Date(2024, 2, 9, 12, 0); // Saturday March 9, 12:00 EST
const plus24h = new Date(start.getTime() + 24 * 3_600_000);
console.log(plus24h.getDate(), plus24h.getHours()); // 10 13 (clock jumped)
const nextDay = new Date(start.getTime());
nextDay.setDate(nextDay.getDate() + 1);
console.log(nextDay.getDate(), nextDay.getHours()); // 10 12 (same wall time)Both results are correct answers to different questions. The bug comes from mixing them up.
Pitfall 2: Counting Days Between Two Dates
Dividing a local-time difference by 86,400,000 gives fractions such as 0.9583 across a spring-forward change. If you then use Math.floor, you are off by a whole day. The reliable approach maps each local calendar date to UTC midnight first, because UTC has no DST:
// Run with: TZ=America/New_York node days-between.js
function calendarDaysBetween(a, b) {
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.round((utcB - utcA) / 86_400_000);
}
const a = new Date(2024, 2, 9, 23, 0); // March 9, 23:00
const b = new Date(2024, 2, 11, 1, 0); // March 11, 01:00
console.log((b - a) / 86_400_000); // 1.0833333333333333
console.log(calendarDaysBetween(a, b)); // 2Math.round is only a safety margin here. Both UTC values fall exactly at midnight, so the division is already exact.
Pitfall 3: Local Times That Do Not Exist or Occur Twice
On the spring-forward day, the wall time 02:30 never happens in New York. On the fall-back day, 01:30 happens twice, once in EDT and once in EST. Date never throws for these times. The specification resolves them in fixed ways:
- In a gap, the engine applies the offset that was in effect before the change. This pushes the result forward by the gap length.
- In an overlap, the engine picks the earlier of the two instants.
// Run with: TZ=America/New_York node gaps.js
const gap = new Date(2024, 2, 10, 2, 30);
console.log(gap.getHours(), gap.getMinutes()); // 3 30
console.log(gap.toISOString()); // "2024-03-10T07:30:00.000Z"
const overlap = new Date(2024, 10, 3, 1, 30);
console.log(overlap.toISOString()); // "2024-11-03T05:30:00.000Z" (EDT, the first 01:30)The Date API gives you no way to ask for the second 01:30 by local components. If your application schedules things at local times close to 01:00 to 03:00, store the intended UTC instant or an explicit offset rather than local components alone.
Pitfall 4: Month-End and Leap-Year Overflow
DST is not the only trap. As you saw earlier, out-of-range fields roll over. That makes "add a month" and "add a year" surprising at the end of a month:
const jan31 = new Date(2024, 0, 31);
const naive = new Date(jan31.getTime());
naive.setMonth(naive.getMonth() + 1);
console.log(naive.toDateString()); // "Sat Mar 02 2024"
const leap = new Date(2024, 1, 29);
leap.setFullYear(2025);
console.log(leap.toDateString()); // "Sat Mar 01 2025"Most business rules want the result clamped to the last valid day. Day 0 of the following month gives you the last day of the current one:
function addMonthsClamped(date, months) {
const result = new Date(date.getTime());
const day = result.getDate();
result.setDate(1); // avoid overflow while changing month
result.setMonth(result.getMonth() + months);
const lastDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
result.setDate(Math.min(day, lastDay));
return result;
}
console.log(addMonthsClamped(new Date(2024, 0, 31), 1).toDateString()); // "Thu Feb 29 2024"
console.log(addMonthsClamped(new Date(2024, 1, 29), 12).toDateString()); // "Fri Feb 28 2025"Setting the day to 1 before changing the month matters. If you skip it, the month change can overflow before you get a chance to clamp. Clamping also loses information, because Jan 31 + 1 month − 1 month gives Jan 29, not Jan 31. Calculate from the original date each time instead of chaining steps.
Pitfall 5: The Date That Shows Up a Day Early
A date-only ISO string such as "2024-03-10" is parsed as UTC midnight. In any zone west of UTC, that instant falls on the previous local day:
// Run with: TZ=America/New_York node early.js
const d = new Date("2024-03-10");
console.log(d.toDateString()); // "Sat Mar 09 2024"
console.log(d.getUTCDate()); // 10You can either read the value back with UTC getters, or format it with timeZone: "UTC" (covered in the Intl chapters), or build it from local components.
Summary of Pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Adding 86,400,000 ms for "one day" | Wall-clock hour shifts across DST | Use `setDate` (local) or `setUTCDate` |
| Dividing a local difference by a day | Fractional or off-by-one day counts | Map dates with `Date.UTC`, then divide |
| Local time in a DST gap | Hour silently moves forward | Validate it, or store UTC instants |
| Local time in a DST overlap | Always resolves to the first occurrence | Store UTC or an explicit offset |
| Midnight-transition zones | Midnight returns as 01:00 | Anchor date-only values at noon |
| Month or year overflow | Jan 31 + 1 month becomes March | Clamp to the last day of the month |
| Date-only ISO strings | Date displays a day early | Use UTC getters or `timeZone: "UTC"` |
Tests that depend on the host's time zone can pass on your laptop and fail in CI, where the zone is often UTC. Pin TZ in your test command. Include at least one DST-observing zone and one zone east of UTC in your test matrix.
Exercise
In America/New_York, a user books a daily standup for 09:00 starting Friday, November 1, 2024. Your code creates each following occurrence by adding 24 * 3,600,000 ms to the previous one. At what local time does the Monday, November 4 occurrence appear, and how should the code be written instead?
Show answer
It appears at 08:00. The fall-back change on November 3 makes that local day 25 hours long, so fixed 24-hour steps fall one hour behind on the wall clock from November 3 onward. Copy the previous date and call setDate(getDate() + 1) so each occurrence keeps 09:00 local time.
Exercise
Why does addMonthsClamped call setDate(1) before setMonth, and what does addMonthsClamped(new Date(2023, 2, 31), -1) return?
Show answer
Without setDate(1), changing March 31 to February would roll over into early March before the clamp runs. With it, the month changes safely to February 2023, the last day is computed as 28, and the result is February 28, 2023 ("Tue Feb 28 2023").