Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

JavaScript Date, Intl and Temporal: Handling Dates and Time Zones

A booking system must distinguish a calendar day from an instant and an appointment at a local wall-clock time. Confusing these concepts causes shifted dates and incorrect bookings.

Published Written by Reading time 12 min read
On this page Contents: quick navigation between sections

Instant, date and local time

Date stores an instant at millisecond precision, not a zone. A birthday is not a UTC instant. Date objects are mutable, numeric constructor months are zero-based, and invalid dates return NaN from getTime(). [1][2]

Parsing and Unix units

unix-seconds.ts

const MILLISECONDS_PER_SECOND = 1000;

export function fromUnixSeconds(seconds: number): Date {
  if (!Number.isSafeInteger(seconds)) {
    throw new RangeError("Expected integer Unix seconds.");
  }

  const date = new Date(seconds * MILLISECONDS_PER_SECOND);

  if (!Number.isFinite(date.getTime())) {
    throw new RangeError("Timestamp outside Date range.");
  }

  return date;
}

Multiply Unix seconds by 1000 before passing them to Date. Never guess units from digit count. An ISO date-only string is interpreted as UTC, while a date-time without an offset uses the host local zone. Define the format and unit explicitly in the API contract. [1][2]

Date and the input contract

parse-utc-timestamp.ts

const UTC_TIMESTAMP_PATTERN =
  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;

export function parseUtcTimestamp(value: string): Date {
  if (!UTC_TIMESTAMP_PATTERN.test(value)) {
    throw new RangeError("Expected a canonical UTC timestamp.");
  }

  const date = new Date(value);

  if (!Number.isFinite(date.getTime()) || date.toISOString() !== value) {
    throw new RangeError("Invalid UTC timestamp.");
  }

  return date;
}

Date stores milliseconds since the Unix epoch, not a zone identifier. Exchange unambiguous UTC timestamps through APIs and store birthdays separately as calendar dates. Date.parse alone is not strict validation: some invalid calendar values can be normalized. The function below deliberately accepts only canonical UTC strings with milliseconds and verifies a round trip. [1][2]

Formatting with Intl

appointment-formatter.ts

export function createAppointmentFormatter(
  locale: string,
  timeZone: string,
): Intl.DateTimeFormat {
  return new Intl.DateTimeFormat(locale, {
    dateStyle: "medium",
    timeStyle: "short",
    timeZone,
  });
}

const formatter = createAppointmentFormatter("pl-PL", "Europe/Warsaw");
const instant = new Date("2026-11-26T14:00:00.000Z");

console.log(formatter.format(instant));

Locale controls presentation; the time zone controls the local clock reading. Do not infer the zone from the language. Specify timeZone for appointment displays. Reuse a formatter for repeated calls; its constructor can throw RangeError for an invalid zone. The formatted output is for people, not for parsing back into data. [3]

Advanced Intl formatting

intl-parts.ts

const formatter = new Intl.DateTimeFormat("pl-PL", {
  timeZone: "Europe/Warsaw",
  hour: "2-digit",
  minute: "2-digit",
  hourCycle: "h23",
});

const start = new Date("2026-11-26T14:00:00Z");
const end = new Date("2026-11-26T15:00:00Z");

console.log(formatter.formatToParts(start));
console.log(formatter.formatRange(start, end));

const relative = new Intl.RelativeTimeFormat("pl-PL", {
  numeric: "auto",
});

console.log(relative.format(-1, "day"));

formatToParts() returns text parts including literals; preserve their order. formatRange() displays an interval, while RelativeTimeFormat formats a supplied number and unit rather than calculating a date difference. Do not parse localized output; test part values rather than full ICU-dependent strings. [3][12][13]

Temporal and daylight saving time

PlainDate represents a calendar day, Instant an exact moment, and ZonedDateTime combines an instant, zone and calendar. In Warsaw, 02:30 on March 29, 2026 does not exist, whereas 02:30 on October 25 occurs twice. Choosing reject forces an explicit resolution instead of silently shifting a booking. This example requires native Temporal or @js-temporal/polyfill. [4][5]

Gaps and overlaps

In Warsaw on 29 March 2026, 02:30 does not exist: earlier gives 01:30 +01:00, later and compatible give 03:30 +02:00. On 25 October, 02:30 occurs twice: earlier and compatible choose +02:00, later chooses +01:00. Reject throws in both cases. In booking flows ask for a choice instead of silently shifting the time. [5][7][8]

Strict appointment contract

resolve-appointment.ts

import { Temporal } from "@js-temporal/polyfill";

const LOCAL_PATTERN =
  /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d$/;
const SUPPORTED_ZONES = new Set(["Europe/Warsaw", "America/New_York"]);

export function resolveAppointment(
  localDateTime: string,
  timeZone: string,
): Temporal.ZonedDateTime {
  if (!LOCAL_PATTERN.test(localDateTime)) {
    throw new RangeError("Expected YYYY-MM-DDTHH:mm.");
  }

  if (!SUPPORTED_ZONES.has(timeZone)) {
    throw new RangeError("Unsupported time zone.");
  }

  const local = Temporal.PlainDateTime.from(localDateTime);

  return local.toZonedDateTime(timeZone, {
    disambiguation: "reject",
  });
}

PlainDateTime parsing can ignore offsets and zone names. Accept only YYYY-MM-DDTHH:mm and a separate zone from the application's allowlist. Reject seconds, offsets, annotations and out-of-range clock fields; Temporal validates the calendar. The example deliberately uses a small allowlist. [7][8]

Storage and calendar arithmetic

calendar-arithmetic.ts

import { Temporal } from "@js-temporal/polyfill";

const start = Temporal.ZonedDateTime.from(
  "2026-03-28T12:00:00+01:00[Europe/Warsaw]",
);

const nextDay = start.add({ days: 1 });
const after24Hours = start.add({ hours: 24 });

console.log(nextDay.hour); // 12
console.log(after24Hours.hour); // 13

Store the UTC instant for completed events. For future appointments also preserve the intended local date and time and IANA zone, because zone rules can change. Calculate recurring events in the calendar. Adding one local day does not always mean 24 hours. An offset such as +01:00 is not a substitute for Europe/Warsaw. [5][6]

PostgreSQL and data modelling

appointments.sql

CREATE TABLE appointments (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  local_start timestamp without time zone NOT NULL,
  time_zone text NOT NULL,
  starts_at timestamptz NOT NULL
);

Use date for birthdays, timestamptz for payment instants, and timestamp without time zone for intended local time. Timestamptz does not retain the zone name; store it separately with the local appointment. PostgreSQL supports microseconds while Date uses milliseconds: define precision-loss rules. If zone rules change, decide whether to preserve the instant or wall time. [9]

Forms, API and SSR

appointment.json

{
  "localDateTime": "2026-11-26T15:00",
  "timeZone": "Europe/Warsaw"
}

A date input supplies a calendar date; datetime-local contains no zone. Send local time and chosen zone separately and revalidate on the server. Hydrate with identical initial text on both sides; even explicit locale and zone may differ across ICU versions. Apply client localization after hydration. [10][11]

Testing edge cases

parse-utc-timestamp.test.ts

import assert from "node:assert/strict";
import { parseUtcTimestamp } from "./parse-utc-timestamp.js";

const valid = "2028-02-29T12:00:00.000Z";

assert.equal(parseUtcTimestamp(valid).toISOString(), valid);
assert.throws(
  () => parseUtcTimestamp("2026-02-30T12:00:00.000Z"),
  RangeError,
);
assert.throws(
  () => parseUtcTimestamp("2026-11-26T12:00:00.000"),
  RangeError,
);

Test rejection of February 30, 2026, missing offsets, out-of-range values, day changes across zones, both clock transitions and leap years. Test under different host zones rather than relying on your development machine. With SSR, choose consistent server and client formatting settings or defer local formatting to the client. [1][3][5]

Store the UTC instant for completed events. For future appointments also preserve the intended local date and time and IANA zone, because zone rules can change. Calculate recurring events in the calendar. Adding one local day does not always mean 24 hours. An offset such as +01:00 is not a substitute for Europe/Warsaw. [5][6]

Tools for this topic

JavaScript TypeScript Date Intl Temporal Time Zones UTC DST

Frequently asked questions

Does a day always have 24 hours?

No. A calendar day in a zone may be shorter or longer during a clock transition. [6]

Does Date retain a time zone?

No. It stores an instant; local methods use the host zone. [1]

How should Unix units be distinguished?

Multiply Unix seconds by 1000 before passing them to Date. Never guess units from digit count. An ISO date-only string is interpreted as UTC, while a date-time without an offset uses the host local zone. Define the format and unit explicitly in the API contract. [1][2]

How do repeated hours work?

In Warsaw on 29 March 2026, 02:30 does not exist: earlier gives 01:30 +01:00, later and compatible give 03:30 +02:00. On 25 October, 02:30 occurs twice: earlier and compatible choose +02:00, later chooses +01:00. Reject throws in both cases. In booking flows ask for a choice instead of silently shifting the time. [5][7][8]

Why validate the local format?

PlainDateTime parsing can ignore offsets and zone names. Accept only YYYY-MM-DDTHH:mm and a separate zone from the application's allowlist. Reject seconds, offsets, annotations and out-of-range clock fields; Temporal validates the calendar. The example deliberately uses a small allowlist. [7][8]

Does timestamptz preserve the zone?

Use date for birthdays, timestamptz for payment instants, and timestamp without time zone for intended local time. Timestamptz does not retain the zone name; store it separately with the local appointment. PostgreSQL supports microseconds while Date uses milliseconds: define precision-loss rules. If zone rules change, decide whether to preserve the instant or wall time. [9]

Does datetime-local include a zone?

A date input supplies a calendar date; datetime-local contains no zone. Send local time and chosen zone separately and revalidate on the server. Hydrate with identical initial text on both sides; even explicit locale and zone may differ across ICU versions. Apply client localization after hydration. [10][11]

Does Intl calculate date differences?

formatToParts() returns text parts including literals; preserve their order. formatRange() displays an interval, while RelativeTimeFormat formats a supplied number and unit rather than calculating a date difference. Do not parse localized output; test part values rather than full ICU-dependent strings. [3][12][13]

Sources and references

  1. MDN, Date↩1↩2↩3↩4↩5↩6↩7
  2. MDN, Date.parse↩1↩2↩3↩4↩5
  3. MDN, Intl.DateTimeFormat↩1↩2↩3↩4↩5
  4. MDN, Temporal↩1↩2
  5. TC39, Time Zones and Resolving Ambiguity↩1↩2↩3↩4↩5↩6↩7
  6. TC39, Temporal.ZonedDateTime↩1↩2↩3
  7. MDN, Temporal.PlainDateTime↩1↩2↩3↩4
  8. MDN, Temporal.PlainDateTime.toZonedDateTime↩1↩2↩3↩4
  9. PostgreSQL, Date/Time Types↩1↩2
  10. MDN, HTML date and time formats↩1↩2
  11. React, hydrateRoot↩1↩2
  12. MDN, formatToParts↩1↩2
  13. MDN, RelativeTimeFormat↩1↩2

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning