Dates and Times in JavaScript From Date to Temporal
A complete guide to dates and times in JavaScript: how Date parses and formats, where time zones and DST break it, and how Temporal replaces it.

Dates look like a small problem until a report is off by a day for users in California, a subscription renews an hour early after a clock change, or a deadline of "end of month" lands on March 3. Every one of those bugs comes from the same source: the word "date" covers four different ideas, and JavaScript's Date object holds only one of them and pretends to hold the rest. This guide separates the ideas, shows exactly how Date behaves with its output, covers parsing, time zones, formatting and arithmetic, and then introduces Temporal, the standard replacement, with the same tasks done again. The examples target Node.js 24 and a Temporal implementation that follows the final specification, supplied by the @js-temporal/polyfill package where the runtime lacks it.
Code that prints a local time depends on the machine's time zone, so every Date example states its zone. Unless a block says otherwise, run it with TZ=UTC, as in TZ=UTC node dates.mjs. The Temporal examples name their zones in the data and do not depend on the machine.
Four ideas that are not one thing
Most date bugs are a mix-up between these, so name them before writing code.
| Idea | Example | Needs a time zone? |
|---|---|---|
| An instant | the moment the page was loaded | No. It is one point on the timeline, the same everywhere |
| A calendar date | a birthday, an invoice date, "2026-05-06" | No. It names a day, not a moment |
| A wall-clock time | "09:30", the time a shop opens | No. It means different instants in different places |
| A zoned date and time | "9:30 on 6 May in Berlin" | Yes. It names an instant and the place whose clock you read |
A log timestamp is an instant. A birthday is a calendar date, and it is the same date in Tokyo and in Lisbon even though midnight comes at different instants. An alarm set for 07:00 is a wall-clock time that you want to fire at 07:00 wherever you are. A flight departing at 09:30 from Berlin on a given day is a zoned date and time, because only the zone tells you which instant that is.
Date stores one number: milliseconds since 1970-01-01T00:00:00Z, which is an instant. Everything else it shows, the year, the month, the day, the hour, is computed from that number by applying a time zone, and which zone it applies depends on the method you call. That design is the root of most of this guide: a birthday stored as a Date is really a birthday at a particular midnight in a particular zone, and it will shift when the zone changes.
What a Date holds
const moment = new Date(Date.UTC(2026, 4, 6, 12, 0, 0));
console.log(moment.getTime());
console.log(moment.toISOString());
console.log(typeof moment, moment instanceof Date);
console.log(Date.UTC(2026, 4, 6, 12) === moment.getTime());1778068800000
2026-05-06T12:00:00.000Z
object true
trueDate.UTC(year, monthIndex, day, hours, minutes, seconds, ms) returns the timestamp for a UTC moment. The month argument is zero-based, so 4 is May. That is the first trap, and every Date method that takes or returns a month shares it, while days of the month start at 1 and hours, minutes and seconds at 0. getTime() and valueOf() return the timestamp, and toISOString() prints it in the format that every API and database understands, in UTC with a Z suffix.
The timestamp has millisecond precision and a range of about 8.64 quadrillion milliseconds either side of 1970, which is plus or minus 100,000,000 days. Beyond that the date is invalid. Inside it, the number is an ordinary number, so arithmetic works, and comparison with < and > works because valueOf() returns it.
const earlier = new Date("2026-05-06T12:00:00Z");
const later = new Date("2026-05-06T12:00:01Z");
console.log(earlier < later);
console.log(later - earlier);
console.log(earlier === new Date("2026-05-06T12:00:00Z"));
console.log(earlier.getTime() === new Date("2026-05-06T12:00:00Z").getTime());true
1000
false
trueSubtraction gives milliseconds, which is why later - earlier is 1000. === compares object identity, so two Date objects for the same moment are not equal. Compare timestamps instead, as the last line does, a rule that follows from how equality works for objects.
Reading parts of a date
A Date has two families of getters: getFullYear, getMonth, getDate, getDay, getHours and so on, which read in the machine's local zone, and getUTCFullYear and the rest, which read in UTC. getDay() returns the weekday with Sunday as 0. getDate() returns the day of the month, and getYear() is a legacy method that you should not call.
const moment = new Date("2026-05-06T23:30:00Z");
console.log(moment.getUTCFullYear(), moment.getUTCMonth(), moment.getUTCDate());
console.log(moment.getUTCDay());
console.log(moment.getUTCHours(), moment.getUTCMinutes());2026 4 6
3
23 30May 6, 2026 is a Wednesday, which is weekday 3. Reading with the UTC getters gives a result that does not depend on where the code runs, so server code that reasons about a calendar day should choose the zone on purpose and either use the UTC getters or an explicit zone with Intl, which a later section shows.
The current time
Date.now() returns the current timestamp, and new Date() with no arguments wraps it. Both read the system clock, which can jump forward or backward when the operating system corrects it. For measuring how long something took, use performance.now(), which is monotonic, in fractional milliseconds from an arbitrary start, and never moves backward.
const t0 = performance.now();
await new Promise((resolve) => setTimeout(resolve, 20));
const elapsed = performance.now() - t0;
console.log(elapsed >= 19);
console.log(Number.isFinite(Date.now()));true
trueThe first check allows a millisecond of slack because timers can fire slightly early relative to the clock's resolution; the exact value changes on every run and is not printed. Date.now() answers "what time is it", and performance.now() answers "how much time has passed", and mixing the two in a duration calculation gives a negative number on the rare day the system clock is stepped back.
Parsing is where the surprises start
new Date(string) and Date.parse(string) accept one format with a fixed definition and a great many formats that the specification leaves to each engine. The defined format is a simplified ISO 8601: YYYY, YYYY-MM, YYYY-MM-DD, and date-times written YYYY-MM-DDTHH:mm, with optional seconds and fraction, and an optional offset, Z or +hh:mm. Everything else, "May 6, 2026", "05/06/2026", "6 May 2026 10:00 PM", is implementation-defined. V8 accepts many of those and other engines accept different ones, and a string that parses in Chrome can be an Invalid Date in Safari.
The rule that causes the most bugs is not about format at all. It is how the missing offset is interpreted, and the two cases differ.
// Run with TZ=America/New_York
const dateOnly = new Date("2026-05-06");
const dateTime = new Date("2026-05-06T00:00:00");
const withOffset = new Date("2026-05-06T00:00:00Z");
console.log(dateOnly.toISOString());
console.log(dateTime.toISOString());
console.log(withOffset.toISOString());
console.log(dateOnly.toString());
console.log(dateTime.toString());2026-05-06T00:00:00.000Z
2026-05-06T04:00:00.000Z
2026-05-06T00:00:00.000Z
Tue May 05 2026 20:00:00 GMT-0400 (Eastern Daylight Time)
Wed May 06 2026 00:00:00 GMT-0400 (Eastern Daylight Time)A date-only string is read as UTC midnight. A date-time string with no offset is read as local time. The inconsistency was settled by the specification this way, and it is why new Date("2026-05-06") formatted with a local getter prints May 5 for every user west of Greenwich. That is the report that is "off by one day for users in California".
The fix is to decide what the string means and say so. If it is an instant, include an offset or Z. If it is a calendar date, do not run it through Date for display at all, or build it from parts in the zone you intend.
function parseCalendarDate(text) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
if (!match) {
throw new RangeError(`not a calendar date: ${text}`);
}
const [, year, month, day] = match.map(Number);
return new Date(year, month - 1, day);
}
// Run with TZ=America/New_York
const day = parseCalendarDate("2026-05-06");
console.log(day.getFullYear(), day.getMonth() + 1, day.getDate());
console.log(day.toISOString());2026 5 6
2026-05-06T04:00:00.000Znew Date(year, monthIndex, day) builds local midnight, so the local getters return the day you meant and the timestamp is the matching instant. The function validates the shape, since the constructor would otherwise accept almost anything. It does not validate the values: "2026-02-30" passes the pattern and produces March 2 as the next section explains, so a stricter version should read the parts back and compare them, a check shown in the validation section below.
Invalid dates
When parsing fails, Date does not throw. It returns an object whose timestamp is NaN.
const broken = new Date("next tuesday");
console.log(String(broken));
console.log(broken.getTime());
console.log(Number.isNaN(broken.getTime()));
try {
broken.toISOString();
} catch (error) {
console.log(error.name + ": " + error.message);
}
console.log(JSON.stringify({ when: broken }));Invalid Date
NaN
true
RangeError: Invalid time value
{"when":null}An invalid Date still has typeof "object" and instanceof Date, so those checks do not catch it. Test with Number.isNaN(date.getTime()). toISOString() throws a RangeError, while JSON.stringify calls toJSON(), which returns null for an invalid date, so a bad date can pass through a serializer and arrive as null on the other side. NaN and why it is not equal to itself explains the check.
A frequent cause is a value that is not a date at all, such as undefined (new Date(undefined) is invalid) or a string with trailing characters. Validate the input where it enters the program, and let the rest of the code assume a valid Date.
Time zones, offsets and daylight saving
A time zone is a set of rules for converting an instant into the wall clock of a place. The rules live in the IANA time zone database, whose names look like Europe/Berlin and America/New_York. An offset such as +02:00 is not a zone. It is one result of applying a zone's rules at one instant. Berlin is +01:00 in January and +02:00 in July, so a stored offset describes one moment and tells you nothing about the zone's rules for any other.
Two things follow that are easy to forget:
A zone's rules change. Governments move daylight saving dates, abolish it or change their standard offset, and the database is updated several times a year. A future local time, such as a meeting at 09:00 next November, has no fixed instant until that date arrives.
A wall-clock time can be missing or doubled. When clocks move forward, the local hour that is skipped does not exist. When they move back, the repeated hour happens twice.
A Date knows its machine's zone, and Node.js reads it from the TZ environment variable or the operating system. Setting process.env.TZ while the process runs works in Node.js, but it is global state for the whole process, so the usual advice for servers is to run in UTC and apply zones only when presenting data.
const instant = new Date("2026-07-01T12:00:00Z");
console.log(instant.getTimezoneOffset());0With TZ=UTC the offset is 0. getTimezoneOffset() returns the difference in minutes between UTC and local time, and its sign is the opposite of what a reader expects: for America/New_York in July it returns 240, and for Asia/Tokyo it returns -540. It also takes the date it is called on into account, so it returns 300 for New York in January. A function that stores getTimezoneOffset() once and applies it to every date is wrong for half the year.
What daylight saving does to a day
On 8 March 2026, clocks in New York moved from 02:00 to 03:00, and that local day was 23 hours long. On 1 November 2026 they moved back, and that local day was 25 hours long. Any code that treats a day as 86,400,000 milliseconds is wrong on those two days.
// Run with TZ=America/New_York
const start = new Date(2026, 2, 8, 0, 0, 0);
const end = new Date(2026, 2, 9, 0, 0, 0);
console.log((end - start) / 3_600_000);
const after = new Date(2026, 2, 8, 2, 30, 0);
console.log(after.getHours(), after.getMinutes());23
3 30Midnight to midnight is 23 hours on that date. The second case asks for 02:30, a time that does not exist in New York on that day, and Date moves forward and answers 03:30. Date has no option to reject or to pick another resolution, which Temporal adds and a later section shows.
Zones other than the machine's
A Date cannot represent a zone other than the machine's. It has the machine zone and UTC, and nothing else. To show an instant in another zone you format it with Intl.DateTimeFormat and a timeZone option.
const instant = new Date("2026-05-06T20:00:00Z");
const options = { dateStyle: "full", timeZone: "Asia/Tokyo" };
console.log(new Intl.DateTimeFormat("en-US", options).format(instant));
const clock = { hour: "2-digit", minute: "2-digit", hourCycle: "h23" };
console.log(
new Intl.DateTimeFormat("en-GB", { ...clock, timeZone: "America/Los_Angeles" }).format(instant),
);
console.log(
new Intl.DateTimeFormat("en-GB", { ...clock, timeZone: "Asia/Tokyo" }).format(instant),
);Thursday, May 7, 2026
13:00
05:00The same instant is the evening of May 6 in Europe and the Americas and the early morning of May 7 in Tokyo. Los Angeles was at UTC-7 on that date because of daylight saving, so 20:00 UTC is 13:00 there. Passing an unknown zone name throws a RangeError, which makes a mistyped zone fail loudly.
Formatting
Format dates for machines and for people in different ways, and keep the two apart.
For machines, use toISOString(), which always gives YYYY-MM-DDTHH:mm:ss.sssZ in UTC. It sorts correctly as text, every language parses it and it contains no zone ambiguity.
For people, use Intl. The default toString() output, Tue May 05 2026 20:00:00 GMT-0400 (Eastern Daylight Time), is a debugging format and not one to show, and toLocaleDateString() is shorthand for Intl.DateTimeFormat that makes a new formatter on every call.
const instant = new Date("2026-05-06T09:15:00Z");
const day = { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" };
console.log(new Intl.DateTimeFormat("en-US", day).format(instant));
console.log(new Intl.DateTimeFormat("de-DE", day).format(instant));
console.log(new Intl.DateTimeFormat("ja-JP", day).format(instant));May 6, 2026
6. Mai 2026
2026年5月6日The order of day, month and year, the month name, the punctuation and the numerals all come from the locale. Writing the format by hand with getMonth() + 1 and string concatenation produces 5/6/2026, which is May 6 to an American reader and June 5 to most of the rest of the world.
Creating a formatter is more costly than calling it, so create one and reuse it when you format many values.
const formatter = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "short",
day: "numeric",
timeZone: "UTC",
});
const releases = [
new Date("2026-01-15T00:00:00Z"),
new Date("2026-06-30T00:00:00Z"),
new Date("2026-12-01T00:00:00Z"),
];
console.log(releases.map((release) => formatter.format(release)));[ 'Jan 15, 2026', 'Jun 30, 2026', 'Dec 1, 2026' ]formatToParts() returns the pieces as an array of { type, value } objects, for when you need to place the month name inside your own markup. Intl.RelativeTimeFormat produces phrases such as "yesterday" and "in 3 days".
const relative = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
console.log(relative.format(-1, "day"));
console.log(relative.format(3, "day"));
console.log(relative.format(-2, "month"));yesterday
in 3 days
2 months agonumeric: "auto" produces "yesterday" and "tomorrow" in place of "1 day ago" and "in 1 day". You decide the unit and the number, and the formatter does the grammar. The Intl API in depth covers numbers and lists with the same pattern.
One formatting trap deserves its own note: a 12-hour time in a recent ICU build, which Node.js 24 uses, separates the time from "AM" or "PM" with a narrow no-break space (U+202F) rather than a plain space. A test that compares formatted output against a string typed with a plain space fails with no visible difference. Prefer hourCycle: "h23" for machine-compared output, or normalize whitespace before comparing.
Arithmetic
Adding time to a date means asking a question that has two different answers, and Date can only answer one of them cleanly.
Elapsed time. "One hour later" and "24 hours later" mean that much time on the timeline, whatever the clock says.
Calendar time. "Tomorrow at the same time" and "next month" mean the same wall-clock time on another date, whatever the elapsed time is.
Elapsed time is millisecond arithmetic, and it is exact.
const HOUR = 3_600_000;
const DAY = 24 * HOUR;
const start = new Date("2026-05-06T12:00:00Z");
const inThirtyHours = new Date(start.getTime() + 30 * HOUR);
const tomorrow = new Date(start.getTime() + DAY);
console.log(inThirtyHours.toISOString());
console.log(tomorrow.toISOString());2026-05-07T18:00:00.000Z
2026-05-07T12:00:00.000ZIn UTC there is no daylight saving, so 24 hours and "one day" are the same here. They are not the same in a zone that has it.
// Run with TZ=America/New_York
const before = new Date(2026, 2, 7, 12, 0, 0);
const byCalendar = new Date(before);
byCalendar.setDate(byCalendar.getDate() + 1);
const byElapsed = new Date(before.getTime() + 24 * 3_600_000);
console.log(before.toISOString());
console.log(byCalendar.toISOString());
console.log(byElapsed.toISOString());2026-03-07T17:00:00.000Z
2026-03-08T16:00:00.000Z
2026-03-08T17:00:00.000ZNoon on 7 March in New York is 17:00 UTC, because the zone was at UTC-5. setDate(getDate() + 1) gives noon on the next calendar day, which is 16:00 UTC because the clocks have moved to UTC-4, so only 23 hours passed. Adding 24 hours gives 17:00 UTC, which a New York wall clock reads as 13:00. A reminder that should say "same time tomorrow" wants the first. A rate limit of 24 hours wants the second.
The setters mutate, and months overflow
Every set method changes the date it is called on and returns the new timestamp, not the date. That is why the example above copies the date first. A function that takes a Date and calls a setter changes the caller's object.
function addDays(date, days) {
date.setUTCDate(date.getUTCDate() + days);
return date;
}
const deadline = new Date("2026-05-06T00:00:00Z");
const extended = addDays(deadline, 7);
console.log(deadline.toISOString());
console.log(extended === deadline);2026-05-13T00:00:00.000Z
trueThe original changed, and the function returned the same object. The safe version copies first: const copy = new Date(date.getTime()). The same mutation is behind bugs where one component adds a day to a shared date and every other component sees it move, a case of the aliasing described in primitives versus objects.
Month arithmetic overflows into the next month rather than clamping.
const date = new Date(Date.UTC(2026, 0, 31));
date.setUTCMonth(date.getUTCMonth() + 1);
console.log(date.toISOString());
const lastOfFebruary = new Date(Date.UTC(2026, 2, 0));
console.log(lastOfFebruary.getUTCDate());
const lastOfLeapFebruary = new Date(Date.UTC(2028, 2, 0));
console.log(lastOfLeapFebruary.getUTCDate());2026-03-03T00:00:00.000Z
28
29January 31 plus one month asks for February 31, which does not exist, so the date rolls forward by the three extra days to March 3. Whether a person means "February 28" or "March 3" depends on the product, and Date chooses March 3 without asking. The trick in the second and third lines uses the same overflow to your advantage: day 0 of a month is the last day of the previous month, so Date.UTC(2026, 2, 0) is February 28 and the getUTCDate() answer is the number of days in February. A helper that clamps explicitly is longer, and it says what it does.
function addMonthsClamped(date, months) {
const result = new Date(date.getTime());
const day = result.getUTCDate();
result.setUTCDate(1);
result.setUTCMonth(result.getUTCMonth() + months);
const lastDay = new Date(
Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0),
).getUTCDate();
result.setUTCDate(Math.min(day, lastDay));
return result;
}
console.log(addMonthsClamped(new Date("2026-01-31T00:00:00Z"), 1).toISOString());
console.log(addMonthsClamped(new Date("2026-03-31T00:00:00Z"), 1).toISOString());
console.log(addMonthsClamped(new Date("2028-01-31T00:00:00Z"), 1).toISOString());2026-02-28T00:00:00.000Z
2026-04-30T00:00:00.000Z
2028-02-29T00:00:00.000ZThe function moves to day 1 so that the month change cannot overflow, applies the month offset, finds how many days the target month has and sets the original day or the last day, whichever is smaller. The third case uses a leap year, which February 2028 is. This is about as much code as a month-clamp should need, and Temporal does it in one call.
Whole days between two dates
The number of days between two calendar dates is a calendar question, and subtracting two local-time Date objects and dividing by 86,400,000 answers an elapsed-time one. The two disagree across a daylight saving change. The reliable approach is to compare the dates as UTC midnights.
function daysBetween(fromText, toText) {
const toUtcDay = (text) => {
const [year, month, day] = text.split("-").map(Number);
return Date.UTC(year, month - 1, day);
};
return Math.round((toUtcDay(toText) - toUtcDay(fromText)) / 86_400_000);
}
console.log(daysBetween("2026-05-06", "2026-12-25"));
console.log(daysBetween("2026-03-07", "2026-03-09"));233
2Both inputs are calendar dates, so the function converts each to the timestamp of its UTC midnight, where every day has the same length, and divides. Math.round absorbs nothing in this case and protects the function if someone later passes timestamps with a leap second or a non-midnight part.
Comparing, sorting and ranges
Two dates compare as numbers, so sorting uses subtraction.
const events = [
{ name: "launch", at: new Date("2026-06-01T09:00:00Z") },
{ name: "kickoff", at: new Date("2026-05-01T09:00:00Z") },
{ name: "review", at: new Date("2026-05-20T09:00:00Z") },
];
events.sort((a, b) => a.at - b.at);
console.log(events.map((event) => event.name));[ 'kickoff', 'review', 'launch' ]a.at - b.at is negative when a is earlier, which puts it first. Without a comparison function, sort() converts items to strings, so it is never what you want for dates.
A time range is best written half-open: it includes its start and excludes its end. "All of 6 May" is from the start of the 6th, included, to the start of the 7th, excluded. Written that way, ranges touch without overlapping or leaving a gap, and the end of one is the start of the next. Closed ranges with an end like 23:59:59.999 leave a one-millisecond hole, and a database column with microseconds falls into it.
function overlaps(a, b) {
return a.start < b.end && b.start < a.end;
}
const morning = {
start: new Date("2026-05-06T09:00:00Z"),
end: new Date("2026-05-06T12:00:00Z"),
};
const noon = {
start: new Date("2026-05-06T12:00:00Z"),
end: new Date("2026-05-06T13:00:00Z"),
};
const lateMorning = {
start: new Date("2026-05-06T11:00:00Z"),
end: new Date("2026-05-06T12:30:00Z"),
};
console.log(overlaps(morning, noon));
console.log(overlaps(morning, lateMorning));false
truemorning ends at 12:00 and noon starts at 12:00, and the half-open rule says they do not overlap, so the test needs only strict comparisons. That single expression is the whole interval-overlap test, and it holds for every pair.
Storing and sending dates
The decision for each field is which of the four ideas it is, and the storage follows from the answer.
| It is | Store as | Example |
|---|---|---|
| An instant that happened | UTC timestamp or ISO string with Z | created_at, a log line, a payment time |
| A calendar date | YYYY-MM-DD text or a date column | a birthday, an invoice date |
| A wall-clock time | HH:mm text | an alarm, an opening hour |
| A future event in a place | local date and time plus the zone name | a meeting at 09:00 in Berlin on 3 November |
The last row is the one most systems get wrong. A future local time stored as a UTC instant has the rules that existed on the day it was written, and if the zone's rules change before the event, the stored instant is an hour off. Storing 2026-11-03T09:00 and Europe/Berlin keeps the intent, and the instant is computed when needed with the then-current rules.
JSON has no date type. JSON.stringify turns a Date into its ISO string, and JSON.parse returns that string, not a Date.
const payload = JSON.stringify({ createdAt: new Date("2026-05-06T12:00:00Z") });
console.log(payload);
const parsed = JSON.parse(payload);
console.log(typeof parsed.createdAt);
const revived = JSON.parse(payload, (key, value) =>
key === "createdAt" ? new Date(value) : value,
);
console.log(revived.createdAt instanceof Date);{"createdAt":"2026-05-06T12:00:00.000Z"}
string
trueA reviver function converts named fields back into dates, as the last lines do. Naming the fields, as in the example, is safer than converting every string that looks like a date, since a free-text field containing a date-shaped string would then change type. JSON in JavaScript covers revivers and toJSON.
A timestamp in seconds is common in other systems, and Date expects milliseconds, so a value from a Unix API needs * 1000. A 10-digit number is seconds and a 13-digit number is milliseconds. That heuristic holds for dates from 2001 to 2286, and a more careful system should name the unit in the field.
Validating a date
A date string that matches a pattern is not a valid date, as 2026-02-30 shows. Validate by building the date and reading it back.
function isRealCalendarDate(text) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
if (!match) return false;
const [, year, month, day] = match.map(Number);
const check = new Date(Date.UTC(year, month - 1, day));
return (
check.getUTCFullYear() === year &&
check.getUTCMonth() === month - 1 &&
check.getUTCDate() === day
);
}
console.log(isRealCalendarDate("2026-02-28"));
console.log(isRealCalendarDate("2026-02-30"));
console.log(isRealCalendarDate("2028-02-29"));
console.log(isRealCalendarDate("2026-13-01"));
console.log(isRealCalendarDate("26-2-3"));true
false
true
false
falseOverflow is detected by round-tripping: if Date.UTC rolled February 30 into March, the month read back is not the month that was put in. The pattern rejects shapes, the round trip rejects values, and the leap-year case passes because February 29, 2028 exists. One more limit: Date.UTC maps the years 0 to 99 onto 1900 to 1999, so a date in the first century needs setUTCFullYear after construction.
Temporal, the replacement
Date cannot be fixed without breaking the web, so the language is getting a new API beside it. Temporal is a TC39 proposal that is at stage 3, with Firefox shipping an implementation and others in progress, and it is expected to be part of ES2027, a status that what is coming in ES2027 tracks. Before relying on it in a browser, check support for your audience. In Node.js 24 it is not enabled by default, and the @js-temporal/polyfill package implements the specification so that the code below runs today; with a native implementation, delete the import and use the global Temporal.
Temporal makes the four ideas separate types, all immutable.
| Type | Holds | Use it for |
|---|---|---|
Temporal.Instant | an exact moment, no zone | timestamps, logs, ordering events |
Temporal.ZonedDateTime | an instant plus a zone and calendar | a flight, a meeting, anything shown in a place |
Temporal.PlainDateTime | a date and a time, no zone | "2026-05-06 09:30" when the zone is implied elsewhere |
Temporal.PlainDate | a calendar date | birthdays, invoice dates, due dates |
Temporal.PlainTime | a wall-clock time | opening hours, alarms |
Temporal.PlainYearMonth, Temporal.PlainMonthDay | a month of a year, a day of a year | a card's expiry, a recurring birthday |
Temporal.Duration | a length of time in units | "1 hour 30 minutes", "3 months" |
Each type tells the reader and the compiler what it knows. A PlainDate has no hour, so there is no midnight to shift when a zone changes, which removes the bug from the parsing section. A ZonedDateTime carries its zone name, so adding a day to it follows that zone's rules.
Everything below uses this import in Node.js 24.
import { Temporal } from "@js-temporal/polyfill";Instants
import { Temporal } from "@js-temporal/polyfill";
const instant = Temporal.Instant.from("2026-05-06T12:00:00Z");
console.log(instant.toString());
console.log(instant.epochMilliseconds);
console.log(instant.toZonedDateTimeISO("Asia/Tokyo").toString());
const fromDate = Temporal.Instant.fromEpochMilliseconds(new Date("2026-05-06T12:00:00Z").getTime());
console.log(instant.equals(fromDate));2026-05-06T12:00:00Z
1778068800000
2026-05-06T21:00:00+09:00[Asia/Tokyo]
trueAn Instant parses an ISO string with an offset or Z and rejects a string without one, because a string with no offset does not name an instant. epochMilliseconds returns the same number as Date.getTime(), and fromEpochMilliseconds is the bridge from an existing Date. toZonedDateTimeISO attaches a zone to get a wall-clock view. The [Asia/Tokyo] suffix is the zone name, written in the string form so that it survives a round trip.
Calendar dates
import { Temporal } from "@js-temporal/polyfill";
const birthday = Temporal.PlainDate.from("2026-05-06");
console.log(birthday.toString());
console.log(birthday.year, birthday.month, birthday.day);
console.log(birthday.dayOfWeek);
console.log(birthday.daysInMonth, birthday.inLeapYear);
console.log(birthday.add({ months: 1 }).toString());2026-05-06
2026 5 6
3
31 false
2026-06-06Months are numbered from 1, so month is 5 for May. dayOfWeek runs from 1 for Monday to 7 for Sunday, which makes 6 May 2026 a 3. The properties daysInMonth and inLeapYear replace the overflow tricks from the Date sections. add returns a new object and leaves birthday unchanged.
The month-end behavior that took a helper function above is a default here, with an option to change it.
import { Temporal } from "@js-temporal/polyfill";
const lastOfJanuary = Temporal.PlainDate.from("2026-01-31");
console.log(lastOfJanuary.add({ months: 1 }).toString());
console.log(lastOfJanuary.add({ months: 2 }).toString());
try {
lastOfJanuary.add({ months: 1 }, { overflow: "reject" });
} catch (error) {
console.log(error.name);
}
try {
Temporal.PlainDate.from({ year: 2026, month: 2, day: 30 }, { overflow: "reject" });
} catch (error) {
console.log(error.name);
}
console.log(Temporal.PlainDate.from({ year: 2026, month: 2, day: 30 }).toString());2026-02-28
2026-03-31
RangeError
RangeError
2026-02-28The default overflow: "constrain" clamps to the last valid day, so January 31 plus one month is February 28, and plus two months is March 31 because the arithmetic is done on the original date, not on the clamped one. With overflow: "reject" an impossible result throws a RangeError, and from() with fields that cannot exist behaves the same way. That makes validation a call to from with reject and a try, in place of the round trip written earlier.
Wall-clock times and combined values
import { Temporal } from "@js-temporal/polyfill";
const opens = Temporal.PlainTime.from("09:30");
console.log(opens.toString());
console.log(opens.add({ hours: 8, minutes: 45 }).toString());
const appointment = Temporal.PlainDateTime.from("2026-05-06T09:30");
console.log(appointment.toString());
console.log(appointment.toPlainDate().toString(), appointment.toPlainTime().toString());09:30:00
18:15:00
2026-05-06T09:30:00
2026-05-06 09:30:00A PlainTime wraps around midnight and has no date. A PlainDateTime joins a date and a time without a zone, which is the right type for a form field where a person types a date and a time and the zone comes from somewhere else, such as the venue. The last line prints two values with a space, which is how console.log separates its arguments.
Zoned date and times
ZonedDateTime is the type for "this wall-clock time in this place", and it is where Temporal does the work that Date could not.
import { Temporal } from "@js-temporal/polyfill";
const meeting = Temporal.ZonedDateTime.from("2026-03-07T12:00:00[America/New_York]");
console.log(meeting.toString());
console.log(meeting.offset, meeting.timeZoneId);
console.log(meeting.epochMilliseconds);
const nextDay = meeting.add({ days: 1 });
const after24h = meeting.add({ hours: 24 });
console.log(nextDay.toString());
console.log(after24h.toString());2026-03-07T12:00:00-05:00[America/New_York]
-05:00 America/New_York
1772902800000
2026-03-08T12:00:00-04:00[America/New_York]
2026-03-08T13:00:00-04:00[America/New_York]This is the daylight saving case again, with the correct answer for each question. add({ days: 1 }) is calendar time: it keeps the wall clock at 12:00 and lets the offset change from -05:00 to -04:00. add({ hours: 24 }) is elapsed time: 24 hours later is 13:00 on the new clock. The distinction is explicit in the unit, since days, weeks, months and years are calendar units and hours, minutes and seconds are exact time.
Gaps and repeats are handled by a disambiguation option instead of a silent choice.
import { Temporal } from "@js-temporal/polyfill";
const gap = "2026-03-08T02:30:00[America/New_York]";
console.log(Temporal.ZonedDateTime.from(gap).toString());
try {
Temporal.ZonedDateTime.from(gap, { disambiguation: "reject" });
} catch (error) {
console.log(error.name);
}
const repeated = "2026-11-01T01:30:00[America/New_York]";
console.log(Temporal.ZonedDateTime.from(repeated).toString());
console.log(Temporal.ZonedDateTime.from(repeated, { disambiguation: "later" }).toString());2026-03-08T03:30:00-04:00[America/New_York]
RangeError
2026-11-01T01:30:00-04:00[America/New_York]
2026-11-01T01:30:00-05:00[America/New_York]The first time does not exist, and the default, compatible, moves it forward by the length of the gap, matching what Date does. With reject you get a RangeError, which is what a booking system wants when a user asks for a time that never happens. The second time happens twice, and the default picks the earlier occurrence, the one at -04:00. later picks the second, at -05:00, and earlier and reject are the other choices. A scheduling feature should pick one on purpose and tell the user what it picked.
Durations and differences
A Duration holds a length in units, and two values give one through until or since.
import { Temporal } from "@js-temporal/polyfill";
const a = Temporal.PlainDate.from("2026-05-06");
const b = Temporal.PlainDate.from("2026-12-25");
console.log(a.until(b).toString());
console.log(a.until(b, { largestUnit: "month" }).toString());
console.log(Temporal.PlainDate.compare(a, b));
const start = Temporal.Instant.from("2026-05-06T12:00:00Z");
const end = Temporal.Instant.from("2026-05-06T14:30:00Z");
console.log(start.until(end).toString());
console.log(start.until(end, { largestUnit: "hour" }).toString());
const pause = Temporal.Duration.from({ hours: 1, minutes: 30 });
console.log(pause.toString(), pause.total({ unit: "minute" }));P233D
P7M19D
-1
PT9000S
PT2H30M
PT1H30M 90The result of until is a Duration, printed in ISO 8601 form: P233D is 233 days, and PT2H30M is two hours and thirty minutes. For dates the default largest unit is days, and asking for months gives P7M19D, from 6 May to 6 December and then 19 more days. For instants the default is seconds, PT9000S, and largestUnit: "hour" gives the readable form. compare returns -1, 0 or 1, ready to hand to sort. total converts a duration to a single number in one unit. The first line's 233 days agrees with the value computed with Date.UTC in the arithmetic section, which makes a useful check when migrating.
Rounding and truncating
import { Temporal } from "@js-temporal/polyfill";
const at = Temporal.ZonedDateTime.from("2026-05-06T17:42:31.250[Europe/Berlin]");
console.log(at.round({ smallestUnit: "minute" }).toString());
console.log(at.round({ smallestUnit: "hour", roundingMode: "floor" }).toString());
console.log(at.startOfDay().toString());2026-05-06T17:43:00+02:00[Europe/Berlin]
2026-05-06T17:00:00+02:00[Europe/Berlin]
2026-05-06T00:00:00+02:00[Europe/Berlin]round takes a smallest unit and a rounding mode, with half-expand, the familiar round-half-up, as the default. startOfDay() gives the first instant of that calendar day in the zone, which is not always 00:00 since some zones skip midnight on a clock change, so it is the method to use instead of building a time of zero. Replacing the pattern of "set hours to zero and subtract a day" with these calls removes a class of off-by-one errors.
Moving from Date to Temporal
Nothing forces a rewrite. The two APIs coexist, and the bridge is the timestamp.
import { Temporal } from "@js-temporal/polyfill";
function toInstant(date) {
return Temporal.Instant.fromEpochMilliseconds(date.getTime());
}
function toDate(instant) {
return new Date(instant.epochMilliseconds);
}
const legacy = new Date("2026-05-06T12:00:00Z");
const instant = toInstant(legacy);
console.log(instant.toString());
console.log(toDate(instant).toISOString());
console.log(toDate(instant.add({ hours: 36 })).toISOString());2026-05-06T12:00:00Z
2026-05-06T12:00:00.000Z
2026-05-07T00:00:00.000ZWrap the boundary with a library that still needs Date, convert at the edges, and use Temporal inside the code you own. Native implementations add Date.prototype.toTemporalInstant() for the same conversion. Inside an application, the order that works is: stop adding new code that uses Date arithmetic, represent calendar dates as PlainDate and future events as ZonedDateTime, and convert an existing Date only where a bug or a rewrite brings you to it.
Three costs belong in the plan. A polyfill adds weight to a front-end bundle that a native implementation does not, so measure it for your page and consider loading it only on the screens that need it. Temporal types serialize as ISO strings and do not round-trip through JSON.parse as dates, so the revival rule above applies with Temporal.Instant.from in place of new Date. And a database driver that returns Date objects needs a conversion step at each row, which a small mapper handles.
Testing code that depends on time
A function that reads the clock is hard to test, because its result changes between runs. Two techniques make it deterministic.
The first is to pass the clock in. A function that takes the current time as an argument is a pure function, and its tests need no tricks.
function isExpired(expiresAt, now = new Date()) {
return now.getTime() >= expiresAt.getTime();
}
const expiresAt = new Date("2026-05-06T12:00:00Z");
console.log(isExpired(expiresAt, new Date("2026-05-06T11:59:59.999Z")));
console.log(isExpired(expiresAt, new Date("2026-05-06T12:00:00Z")));false
trueThe default argument keeps the call site simple in production, and a test passes the moment it wants to check, including both sides of the boundary: one millisecond before and exactly at expiry.
The second is to fake the clock for code that calls Date.now() itself. The Node.js test runner can mock Date.
import { test } from "node:test";
import assert from "node:assert/strict";
function greeting() {
const hour = new Date().getUTCHours();
return hour < 12 ? "good morning" : "good afternoon";
}
test("greeting follows the clock", (context) => {
context.mock.timers.enable({ apis: ["Date"], now: new Date("2026-05-06T08:00:00Z") });
assert.equal(greeting(), "good morning");
context.mock.timers.tick(5 * 3_600_000);
assert.equal(greeting(), "good afternoon");
});✔ greeting follows the clock (1.1ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 48.7With Date mocked, the clock starts at the now option and moves only when the test calls tick, so five hours pass instantly and the second assertion sees 13:00. The timing figures differ from run to run. Passing the clock in is better where you can do it, since it needs no global patching, and the mock is for code you do not control. Test the two days a year when the clocks change, a boundary at the end of February in a leap year and a date near the end of a month, since those are where the bugs in this guide live.
Libraries
The libraries that grew around Date's problems still have a job. date-fns offers small functions over plain Date objects, such as addMonths that clamps, and tree-shakes well. Luxon wraps Date in immutable objects with zone support and is a close cousin of Temporal's model. Day.js is a small wrapper with an API like Moment's, and Moment itself is in maintenance and is not recommended for new work by its own maintainers.
The choice today is narrow. For a new project that must run in browsers where Temporal is not yet available, use the polyfill or Luxon, depending on whether you prefer the standard's API or a mature one with a larger body of examples. For an existing project built on date-fns or Day.js that works, leave it. When Temporal is native in every runtime you support, prefer it and drop the dependency, because nothing the library offers will be missing.
A catalogue of date bugs
Each of these has appeared in this guide, and most are one decision away from not happening.
| Symptom | Cause | Fix |
|---|---|---|
| A date shows as the previous day for western users | new Date("YYYY-MM-DD") is UTC midnight, read with local getters | Treat the value as a calendar date, or read with UTC getters, or use PlainDate |
| The month is off by one | getMonth() and the month argument start at 0 | Add 1 on the way out, subtract 1 on the way in, or use Temporal |
| A date of January 31 plus a month is March | setMonth overflows | Clamp the day, or use PlainDate.add |
| "Same time tomorrow" is an hour out twice a year | Added 24 hours of elapsed time | Add one calendar day, in a zone-aware type |
| A function changes its argument | Date setters mutate | Copy first, or use Temporal's immutable types |
Two equal dates are not === | Objects compare by identity | Compare getTime() or use equals |
An invalid date reaches the database as null | toJSON returns null, no exception | Validate at the boundary |
| A string with a weekday name parses in one browser only | Non-ISO formats are implementation-defined | Accept ISO strings, or parse with a rule you own |
| A future appointment moves an hour | Stored as an instant, then a rule changed | Store the local time and the zone name |
| A sort puts dates in the wrong order | sort() without a comparison compares strings | (a, b) => a - b |
A worked example: a weekly meeting across a clock change
A recurring meeting is the case that shows the difference between instants and zoned times most clearly. The meeting is every Monday at 09:00 in Berlin, starting on 23 March 2026. Clocks in Germany move forward on Sunday 29 March, so the first and the second meeting are six days and 23 hours apart in elapsed time.
The first implementation uses Date and adds seven days of milliseconds each week.
const first = new Date("2026-03-23T08:00:00Z");
const berlinClock = new Intl.DateTimeFormat("en-GB", {
timeZone: "Europe/Berlin",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
});
for (let week = 0; week < 3; week += 1) {
const slot = new Date(first.getTime() + week * 7 * 86_400_000);
console.log(slot.toISOString(), berlinClock.format(slot));
}2026-03-23T08:00:00.000Z 09:00
2026-03-30T08:00:00.000Z 10:00
2026-04-06T08:00:00.000Z 10:00The meeting drifts to 10:00 local time from the second week, because the code kept the UTC time fixed and the Berlin offset changed from one hour to two. Everyone in Berlin shows up an hour late, and no line of the code looks wrong.
The second implementation keeps the wall clock fixed and lets the instant move.
import { Temporal } from "@js-temporal/polyfill";
function weekly(start, count) {
const slots = [];
let current = start;
for (let week = 0; week < count; week += 1) {
slots.push(current);
current = current.add({ weeks: 1 });
}
return slots;
}
const first = Temporal.ZonedDateTime.from("2026-03-23T09:00:00[Europe/Berlin]");
for (const slot of weekly(first, 3)) {
console.log(slot.toString(), slot.toInstant().toString());
}2026-03-23T09:00:00+01:00[Europe/Berlin] 2026-03-23T08:00:00Z
2026-03-30T09:00:00+02:00[Europe/Berlin] 2026-03-30T07:00:00Z
2026-04-06T09:00:00+02:00[Europe/Berlin] 2026-04-06T07:00:00ZEvery slot is 09:00 in Berlin, and the instants behind them move from 08:00 UTC to 07:00 UTC when the clocks change, as they should. The data to store for this meeting is the first slot's local date and time, the zone name and the rule "every week", and each occurrence is computed when needed, so a change in the zone's rules reaches all future meetings without a data migration. For people in other zones, convert each ZonedDateTime to theirs with withTimeZone("America/New_York"), and their own clocks change on a different date, which is why a Berlin-to-New-York meeting is an hour closer or further apart for two weeks of March.
Where these rules stop
The model in this guide covers the Gregorian calendar and the IANA zone database, which is what nearly every application needs. It does not cover everything.
Other calendars exist. Temporal supports them through a calendar option, and Intl.DateTimeFormat formats Islamic, Hebrew, Japanese and other calendars when you ask for them, but the arithmetic and the edge cases of a lunar or era-based calendar are specific to each, and a product that needs one should test with real users of that calendar.
Historical dates have their own problems. The Gregorian reform happened on different days in different countries, Date uses a proleptic Gregorian calendar that extends the rules backward, and time zone offsets before standardization were local mean time. A system storing dates before about 1900 should treat the zone database's early entries as approximate.
Leap seconds are invisible: Date and Temporal both count as if every day had 86,400 seconds, and the operating system smears or steps the clock around the extra second. That is the right choice for application code, and it means an exact-duration claim across a leap second is not something JavaScript can check.
Finally, the clock itself is untrusted. A device's clock can be wrong, and a timestamp from a browser describes what the user's machine said, not when the server received the request. Security checks, token expiry and ordering across machines should use the server's clock, and ordering across servers should use a logical clock or an id that carries order, because no two clocks are in step.


