Glossary / Date and time handling
Date and time handling
JavaScript’s legacy Date represents an instant as milliseconds from the Unix epoch, but its API mixes UTC and host-local operations and has parsing pitfalls. Reliable date handling begins by distinguishing an instant, a calendar date without a time zone, a local wall-clock time, and a duration. These concepts have different domain meaning and should not be represented interchangeably.
What Date represents
const instant = new Date("2026-03-10T14:00:00Z");
instant.toISOString(); // UTC representation of the instant
instant.getHours(); // Host-local hour
instant.getUTCHours(); // UTC hour
A Date stores an instant; it does not retain an IANA time-zone identity or original string. Local getters use the machine’s time zone; UTC getters do not. Date-only values (birthday, invoice date) should not casually be converted to UTC midnight, which can display as the previous day elsewhere. Local appointment times can be ambiguous or nonexistent during daylight-saving transitions.
Use Intl.DateTimeFormat for localized display and specify timeZone when output must be deterministic. Parsing non-standard date strings is unreliable; use ISO input or an explicit parser and validation contract. Date has millisecond precision and historical design limitations. The Temporal API offers more explicit types in supporting runtimes; availability and polyfill requirements vary.
Testing and storage
Inject clocks for deterministic “now” behavior. Test leap days, year boundaries, midnight, daylight-saving gaps/overlaps, and multiple zones. Store instants canonically, but preserve named time zones and local recurrence rules for recurring schedules. Keep durations as durations rather than interpreting them as calendar dates.
Interview questions
- What does Date store? An epoch-millisecond instant.
- Does Date remember the source time zone? No.
- Why can a date-only value shift by a day? Treating it as an instant and formatting in a different zone can cross midnight.
- How test date logic? Inject a clock and pin locale/time zone; cover DST and calendar boundaries.