JavaScript dates become predictable when you separate storage, parsing, comparison, and display. This cookbook provides copy-ready recipes with Intl.DateTimeFormat, Intl.RelativeTimeFormat, UTC-safe patterns, time-zone conversion, date-only handling, and tests for daylight-saving transitions and invalid input.
Overview
A JavaScript Date represents a single instant: a number of milliseconds since the Unix epoch. It does not store a time zone. A time zone enters the picture when you parse a value, call a local-time method, or format the instant for a person.
That distinction explains many common bugs. The same instant can be displayed as different clock times in New York, London, and Tokyo, while a date such as a birthday or billing due date may not represent an instant at all. Before writing a formatter, decide which kind of value you have:
- Instant: an event that happened at one moment, such as a log entry or API request.
- Calendar date: a date without a time zone, such as a birthday or holiday.
- Local date and time: a wall-clock value whose intended time zone must be known, such as a store opening time.
- Duration: an amount of elapsed time, such as 90 minutes. A duration is not a date.
Use ISO 8601 strings in UTC for instants at API boundaries, for example 2026-11-05T14:30:00.000Z. Keep date-only values as date-only values rather than silently converting them to midnight in the browser's local time zone.
What to track
Format an instant for a user's locale
Intl.DateTimeFormat is the preferred built-in tool for localized display. Pass the locale and time-zone policy explicitly instead of relying on the browser defaults when the output matters.
const instant = new Date('2026-11-05T14:30:00Z');
const formatter = new Intl.DateTimeFormat('en-GB', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'Europe/London'
});
console.log(formatter.format(instant));
// Example shape: 5 Nov 2026, 14:30
For a user's own time zone, obtain it from an intentional application setting or, when appropriate, from the browser:
const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const text = new Intl.DateTimeFormat('en-US', {
dateStyle: 'long',
timeStyle: 'short',
timeZone: userTimeZone
}).format(instant);
Do not assume that a locale determines a time zone. en-US describes language and regional formatting conventions; it does not identify a specific city or offset.
Format a date-only value without an accidental shift
The string 2026-11-05 is commonly parsed as a UTC date by JavaScript's ISO date parsing rules. Formatting that value in a western time zone can show the previous calendar day. If the value is a calendar date, format its components directly or use a date-only type in a date library.
function formatDateOnly(value, locale = 'en-US') {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (!match) throw new Error('Expected YYYY-MM-DD');
const [, year, month, day] = match;
const date = new Date(Number(year), Number(month) - 1, Number(day));
return new Intl.DateTimeFormat(locale, {
dateStyle: 'long'
}).format(date);
}
console.log(formatDateOnly('2026-11-05'));
This approach constructs local midnight, so it is suitable for display in the current environment when the value is explicitly a local calendar date. For a date belonging to another time zone, use that zone deliberately rather than treating local midnight as universal.
Display relative time
Use Intl.RelativeTimeFormat for labels such as “in 3 days” or “2 hours ago.” Choose the unit based on the size of the difference and keep the calculation in milliseconds.
function relativeTime(target, reference = new Date(), locale = 'en') {
const difference = new Date(target).getTime() - reference.getTime();
const seconds = Math.round(difference / 1000);
const units = [
['year', 31_536_000],
['month', 2_592_000],
['day', 86_400],
['hour', 3_600],
['minute', 60],
['second', 1]
];
for (const [unit, size] of units) {
if (Math.abs(seconds) >= size || unit === 'second') {
const value = Math.round(seconds / size);
return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
.format(value, unit);
}
}
}
console.log(relativeTime('2026-11-08T14:30:00Z', new Date('2026-11-05T14:30:00Z')));
// in 3 days
The month and year sizes in this compact example are approximations for relative labels. If calendar-accurate month arithmetic matters, use a calendar-aware approach rather than converting months to a fixed number of seconds.
Compare instants and validate input
function parseInstant(value) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
throw new TypeError(`Invalid date: ${value}`);
}
return date;
}
const start = parseInstant('2026-11-05T09:00:00Z');
const end = parseInstant('2026-11-05T10:30:00Z');
if (end.getTime() > start.getTime()) {
console.log('The end is after the start');
}
Never compare date strings unless their format and ordering rules are guaranteed. ISO strings with the same precision and offset can sort correctly lexicographically, but mixed offsets, missing components, or localized strings should be parsed first.
Cadence and checkpoints
Use this decision table when implementing a new date field. It keeps storage and presentation concerns separate:
| Requirement | Recommended representation | Display approach |
|---|---|---|
| Event occurred at one instant | UTC ISO string with Z, or epoch milliseconds | Format with Intl.DateTimeFormat and an explicit zone |
| User's birthday | YYYY-MM-DD date-only value | Format calendar components without UTC conversion |
| Meeting in a named region | Local date-time plus an IANA zone such as America/New_York | Convert and format with that named zone |
| Elapsed work time | Milliseconds or a numeric duration | Calculate units; do not format as a calendar date |
At implementation checkpoints, verify four paths: the value sent by the API, the value parsed by the client, the time zone used for display, and the value submitted by an edit form. A formatter can make an incorrect value look polished, so inspect the underlying value in tests and browser tools.
For recurring jobs and backend integrations, document whether the schedule is UTC or tied to a named IANA time zone. If date calculations also occur in a database, compare the application rule with the database's date and time functions; the syntax and defaults differ across PostgreSQL, MySQL, SQLite, and SQL Server. See the SQL date and time functions guide when the same value crosses that boundary.
How to interpret changes
Most timezone bugs are not formatter bugs. They are contract bugs. A server may send a timestamp without an offset, a form may treat a date-only field as midnight UTC, or a component may call toLocaleString() and silently use the machine's zone. Trace the value from origin to screen before changing display code.
Daylight-saving transitions deserve explicit tests. A local clock can skip a range of times when clocks move forward and repeat a range when clocks move backward. Test an instant immediately before and after each relevant transition, and test the same instant in at least two named zones.
const cases = [
{ value: '2026-03-08T06:59:59Z', zone: 'America/New_York' },
{ value: '2026-03-08T07:00:00Z', zone: 'America/New_York' },
{ value: '2026-11-01T05:59:59Z', zone: 'America/New_York' },
{ value: '2026-11-01T06:00:00Z', zone: 'America/New_York' }
];
for (const test of cases) {
const output = new Intl.DateTimeFormat('en-US', {
dateStyle: 'short',
timeStyle: 'long',
timeZone: test.zone
}).format(new Date(test.value));
console.log(test.value, output);
}
Treat invalid input as an expected state. Check for Number.isNaN(date.getTime()), reject ambiguous formats, and return a useful validation message. Also test empty strings, impossible dates, missing offsets, and values supplied by users in a locale-specific format.
Temporal is designed to make distinctions such as instant, plain date, zoned date-time, and duration more explicit. Where your supported runtime and tooling provide it, evaluate Temporal.Instant for instants, Temporal.PlainDate for date-only values, and Temporal.ZonedDateTime for a date-time tied to a named zone. Treat it as an adoption decision for your project rather than mixing types casually with legacy Date.
When to revisit
Revisit this guide whenever a new date field, calendar, reminder, report, or scheduled workflow is added. A lightweight monthly or quarterly review is useful for shared UI components: check that formatters still receive an explicit locale and zone, that date-only fields remain date-only, and that invalid input is tested.
Run a focused review after browser, runtime, framework, or internationalization-library updates. Also revisit the implementation when product requirements expand to new locales, calendars, regions, or recurring events. Browser and runtime support for newer APIs can change, so verify the compatibility target used by your application before relying on Temporal or newer Intl options.
For a practical checklist:
- Label every field as an instant, calendar date, local date-time, or duration.
- Choose a transport representation and document its offset or time-zone rule.
- Parse and validate at the boundary; do not pass ambiguous strings deep into the UI.
- Format with
Intl.DateTimeFormat, specifying locale and time zone where needed. - Test invalid input, UTC boundaries, daylight-saving transitions, and at least one non-default locale.
- Record the decision in the component or API documentation so the next change does not recreate the bug.
Keep these checks near the code that owns the date contract. The result is not merely a nicer date display; it is a predictable boundary between machine time, calendar meaning, and the user's local context.