Dates and time
suggest changeJavaScript's built-in Date dates from 1995 and has well-known problems: months count from 0, objects are mutable, parsing is lenient, and it only knows two time zones (UTC and the machine's local zone). Still, with a few rules and the Intl APIs it covers most server-side needs, and the new Temporal API is starting to arrive in Node.js.
| Task | API |
|---|---|
| Current time in milliseconds | Date.now() |
| A point in time | new Date(...) |
| Machine-readable string | date.toISOString() |
| Human-readable string in any locale or time zone | Intl.DateTimeFormat |
| "3 hours ago" | Intl.RelativeTimeFormat |
| "1 hour, 46 minutes" | Intl.DurationFormat |
| Measuring elapsed time | performance.now(), process.hrtime.bigint() |
| Calendar math with time zones | Temporal (experimental in Node.js 24) or a library |
The examples are ES modules (save them as .mjs) and were run with Node.js 24 with the environment variable TZ=America/New_York, so "local time" in the output means New York time.
What a Date is
A Date is a single number: milliseconds since the Unix epoch (1970-01-01T00:00:00Z). It has no time zone of its own. Methods like getHours() or toString() interpret that number in the process's local zone, and the getUTC*() methods and toISOString() interpret it in UTC.
const now = new Date();
console.log(now instanceof Date, typeof Date.now());
const epoch = new Date(0);
console.log(epoch.toISOString());
const fromMs = new Date(1_773_000_000_000);
console.log(fromMs.toISOString(), fromMs.getTime());
// year, monthIndex (0-11!), day, hours, minutes, seconds, ms -- local time
const local = new Date(2026, 2, 15, 9, 30);
console.log(local.toString());
console.log(local.toISOString());
// the same components interpreted as UTC
const utc = new Date(Date.UTC(2026, 2, 15, 9, 30));
console.log(utc.toISOString());
true number
1970-01-01T00:00:00.000Z
2026-03-08T20:00:00.000Z 1773000000000
Sun Mar 15 2026 09:30:00 GMT-0400 (Eastern Daylight Time)
2026-03-15T13:30:00.000Z
2026-03-15T09:30:00.000Z
Note that 2 means March: the month index is 0-based, while the day of month is 1-based. Date.now() returns the same number as new Date().getTime() without allocating an object.
Parsing strings
The only format the specification guarantees is the ISO 8601 subset YYYY-MM-DDTHH:mm:ss.sssZ. Even within it there is a trap: a date-only string is treated as UTC, but a date-time without an offset is treated as local time.
console.log(new Date('2026-03-15').toISOString()); // date-only: UTC
console.log(new Date('2026-03-15T09:30').toISOString()); // no offset: local
console.log(new Date('2026-03-15T09:30Z').toISOString()); // Z: UTC
console.log(new Date('2026-03-15T09:30+05:30').toISOString());
const bad = new Date('15/03/2026');
console.log(bad.getTime(), String(bad));
try {
bad.toISOString();
} catch (err) {
console.log(err.name, err.message);
}
function parseDate(s) {
const d = new Date(s);
if (Number.isNaN(d.getTime())) throw new Error(`invalid date: ${s}`);
return d;
}
console.log(parseDate('2026-10-17T08:00:00Z').toISOString());
console.log(Date.parse('2026-03-15T09:30:00Z'));
// lenient, implementation-specific parsing: avoid
console.log(new Date('March 7, 2026').toISOString());
console.log(new Date('2026-02-31').toISOString()); // no error!
2026-03-15T00:00:00.000Z
2026-03-15T13:30:00.000Z
2026-03-15T09:30:00.000Z
2026-03-15T04:00:00.000Z
NaN Invalid Date
RangeError Invalid time value
2026-10-17T08:00:00.000Z
1773567000000
2026-03-07T05:00:00.000Z
2026-03-03T00:00:00.000Z
Rules that follow from this:
- An unparseable string doesn't throw; you get an "Invalid Date" whose time value is
NaN. Check withNumber.isNaN(d.getTime()). CallingtoISOString()on it throws aRangeError. - Always include
Zor an explicit offset in timestamps you store or send over the network. - V8 accepts many non-standard formats (
'March 7, 2026') and silently rolls over impossible dates like February 31. For user input in a known format such asdd/MM/yyyy, parse it yourself or use a library (see Libraries below).
Reading components: local vs UTC
Every getter has a local and a UTC version. On a server, the local version depends on the machine's time zone, which is a common source of "works on my machine" bugs.
const d = new Date('2026-03-15T02:30:00Z');
console.log('local:', d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getDay());
console.log('utc: ', d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCDay());
console.log('offset minutes:', d.getTimezoneOffset());
local: 2026 2 14 22 6
utc: 2026 2 15 2 0
offset minutes: 240
The same instant is Saturday the 14th in New York and Sunday the 15th in UTC. getDay() returns 0 for Sunday through 6 for Saturday. getTimezoneOffset() is UTC minus local time in minutes, so it is positive for zones west of Greenwich, the opposite sign of the usual -04:00 notation.
Dates are mutable
The set*() methods change the object in place. A function that receives a Date and modifies it changes the caller's value too:
function endOfDay(date) {
date.setHours(23, 59, 59, 999); // modifies the caller's object!
return date;
}
const start = new Date(2026, 0, 10, 8, 0);
const end = endOfDay(start);
console.log(start === end, start.toString());
function endOfDaySafe(date) {
const copy = new Date(date); // copy first
copy.setHours(23, 59, 59, 999);
return copy;
}
const s2 = new Date(2026, 0, 10, 8, 0);
endOfDaySafe(s2);
console.log(s2.toString());
true Sat Jan 10 2026 23:59:59 GMT-0500 (Eastern Standard Time)
Sat Jan 10 2026 08:00:00 GMT-0500 (Eastern Standard Time)
new Date(otherDate) makes a copy. Treat dates as immutable values: copy, then modify the copy.
Comparing and sorting
== and === compare object identity, not time. Relational operators and subtraction convert dates to numbers, so they work as expected:
const a = new Date('2026-01-01T00:00:00Z');
const b = new Date('2026-01-01T00:00:00Z');
console.log(a === b, a.getTime() === b.getTime(), a < new Date('2026-06-01'));
const sorted = [new Date('2026-05-01'), new Date('2025-12-24'), new Date('2026-01-15')]
.sort((x, y) => x - y)
.map((x) => x.toISOString().slice(0, 10));
console.log(sorted);
false true true
[ '2025-12-24', '2026-01-15', '2026-05-01' ]
Built-in string conversions
const d = new Date('2026-07-04T18:05:09.123Z');
console.log(d.toISOString());
console.log(d.toJSON());
console.log(d.toString());
console.log(d.toUTCString());
console.log(d.toDateString());
console.log(d.toLocaleString('en-US'));
console.log(d.toLocaleString('de-DE'));
console.log(d.toLocaleDateString('en-GB'));
console.log(d.toLocaleTimeString('ja-JP'));
2026-07-04T18:05:09.123Z
2026-07-04T18:05:09.123Z
Sat Jul 04 2026 14:05:09 GMT-0400 (Eastern Daylight Time)
Sat, 04 Jul 2026 18:05:09 GMT
Sat Jul 04 2026
7/4/2026, 2:05:09 PM
4.7.2026, 14:05:09
04/07/2026
14:05:09
toISOString()is the format to use for logs, databases and APIs: always UTC, sortable as a string, and parsed back exactly bynew Date().toUTCString()produces the RFC 7231 format used by HTTP headers such asLast-ModifiedandExpires.toLocale*String()accept the same locale and options asIntl.DateTimeFormat. Node.js ships with full ICU data, so all locales are available.
Formatting with Intl.DateTimeFormat
Intl.DateTimeFormat formats an instant for a given locale and, crucially, in any IANA time zone:
const d = new Date('2026-07-04T18:05:09.123Z');
const long = new Intl.DateTimeFormat('en-US', {
dateStyle: 'full',
timeStyle: 'long',
timeZone: 'Europe/Paris',
});
console.log(long.format(d));
const custom = new Intl.DateTimeFormat('en-US', {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false,
timeZone: 'Asia/Tokyo',
timeZoneName: 'short',
});
console.log(custom.format(d));
for (const locale of ['en-US', 'fr-FR', 'pl-PL', 'zh-CN']) {
console.log(locale.padEnd(6), new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(d));
}
// formatting many dates: create the formatter once and reuse it
const fmt = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
console.log(['2026-01-05', '2026-02-14', '2026-12-25'].map((s) => fmt.format(new Date(s))));
console.log(fmt.formatRange(new Date('2026-01-05'), new Date('2026-01-09')));
Saturday, July 4, 2026 at 8:05:09 PM GMT+2
Sun, Jul 5, 2026, 03:05 GMT+9
en-US Jul 4, 2026
fr-FR 4 juil. 2026
pl-PL 4 lip 2026
zh-CN 2026年7月4日
[ 'Jan 5', 'Feb 14', 'Dec 25' ]
Jan 5 – 9
dateStyle/timeStyle('full','long','medium','short') can't be combined with individual fields likemonthorhour.- Creating a formatter is relatively expensive. In a loop or a request handler, create it once and call
format()many times. - Locale output is meant for humans and can change between ICU versions (spaces may be non-breaking or thin spaces). Never parse it back or compare it in tests against hard-coded strings that you didn't generate with the same Node.js version.
Building a custom format with formatToParts
There is no strftime-style format string in the standard library. formatToParts() returns the pieces, which you can assemble in any layout, in any time zone:
// "YYYY-MM-DD HH:mm:ss" in a given time zone, built from parts
function formatInZone(date, timeZone) {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone,
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hourCycle: 'h23',
}).formatToParts(date);
const p = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}
const d = new Date('2026-07-04T18:05:09Z');
console.log(formatInZone(d, 'UTC'));
console.log(formatInZone(d, 'America/Los_Angeles'));
console.log(formatInZone(d, 'Asia/Kolkata'));
// simple local "YYYY-MM-DD" without Intl
const pad = (n) => String(n).padStart(2, '0');
const local = new Date(2026, 0, 5, 21, 0); // 9 PM local
console.log(`${local.getFullYear()}-${pad(local.getMonth() + 1)}-${pad(local.getDate())}`);
console.log(local.toISOString().slice(0, 10)); // careful: this is the UTC date
2026-07-04 18:05:09
2026-07-04 11:05:09
2026-07-04 23:35:09
2026-01-05
2026-01-06
The last line shows a frequent bug: toISOString().slice(0, 10) gives the date in UTC, which at 9 PM in New York is already the next day. hourCycle: 'h23' avoids 24:00 for midnight, which some locales produce with hour12: false.
Time zones
The process's local zone comes from the TZ environment variable, or from the operating system if TZ isn't set:
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
console.log(process.env.TZ);
// offset of a zone at a given instant
function zoneOffset(date, timeZone) {
const parts = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' })
.formatToParts(date);
return parts.find((p) => p.type === 'timeZoneName').value;
}
const winter = new Date('2026-01-15T12:00:00Z');
const summer = new Date('2026-07-15T12:00:00Z');
for (const tz of ['America/New_York', 'Europe/London', 'Asia/Kolkata', 'Australia/Sydney']) {
console.log(tz.padEnd(18), zoneOffset(winter, tz), zoneOffset(summer, tz));
}
console.log(Intl.supportedValuesOf('timeZone').length);
try {
new Intl.DateTimeFormat('en-US', { timeZone: 'Mars/Olympus' });
} catch (err) {
console.log(err.name, err.message);
}
America/New_York
America/New_York
America/New_York GMT-05:00 GMT-04:00
Europe/London GMT+00:00 GMT+01:00
Asia/Kolkata GMT+05:30 GMT+05:30
Australia/Sydney GMT+11:00 GMT+10:00
418
RangeError Invalid time zone specified: Mars/Olympus
Offsets change with daylight saving time, and the southern hemisphere switches in the opposite direction. That's why you should store a zone name like Europe/London, not an offset like +01:00, when you need to know a user's local time in the future.
Node.js also lets you change process.env.TZ at runtime, and subsequent local-time methods pick up the new zone:
const d = new Date('2026-07-04T18:00:00Z');
console.log(d.getHours());
process.env.TZ = 'Asia/Tokyo';
console.log(d.getHours());
$ TZ=UTC node tz.mjs
18
3
Changing it in the middle of a program affects all code in the process, so do it only in tests or at the very top of the entry point. Better yet, run servers with TZ=UTC (many container images do by default) and pass an explicit timeZone to Intl.DateTimeFormat whenever you show a time to a user. Then the server's location doesn't affect any result.
Date arithmetic
Adding hours, minutes or seconds is plain millisecond arithmetic. Adding days, months or years is calendar arithmetic, and the two differ around daylight saving time changes:
const DAY_MS = 24 * 60 * 60 * 1000;
function addDays(date, days) {
const d = new Date(date);
d.setDate(d.getDate() + days); // overflow rolls into the next month/year
return d;
}
const d = new Date(2026, 0, 30, 10, 0);
console.log(addDays(d, 3).toDateString());
console.log(addDays(d, -30).toDateString());
// DST: on 2026-03-08 New York clocks jump from 2:00 to 3:00
const beforeDst = new Date(2026, 2, 7, 12, 0);
console.log(new Date(beforeDst.getTime() + DAY_MS).toString()); // + 24 hours
console.log(addDays(beforeDst, 1).toString()); // same wall clock time
Mon Feb 02 2026
Wed Dec 31 2025
Sun Mar 08 2026 13:00:00 GMT-0400 (Eastern Daylight Time)
Sun Mar 08 2026 12:00:00 GMT-0400 (Eastern Daylight Time)
setDate() with an out-of-range value rolls over correctly into neighbouring months and years. Adding 24 * 60 * 60 * 1000 lands at 1 PM, because that day had only 23 hours. Use milliseconds for "24 hours from now" (expiry times, timeouts) and setDate() for "same time tomorrow" (reminders, schedules).
Adding months
Months have different lengths, so "January 31 plus one month" needs a decision. setMonth() overflows into March; usually you want to clamp to the last day of the month:
function addMonths(date, months) {
const d = new Date(date);
const day = d.getDate();
d.setDate(1);
d.setMonth(d.getMonth() + months);
const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
d.setDate(Math.min(day, lastDay));
return d;
}
const jan31 = new Date(2026, 0, 31);
const naive = new Date(jan31);
naive.setMonth(naive.getMonth() + 1);
console.log(naive.toDateString()); // overflowed into March
console.log(addMonths(jan31, 1).toDateString()); // clamped
console.log(addMonths(new Date(2028, 0, 31), 1).toDateString());
// day 0 of next month is the last day of this month
const daysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
console.log(daysInMonth(2026, 1), daysInMonth(2028, 1), daysInMonth(2026, 3));
Tue Mar 03 2026
Sat Feb 28 2026
Tue Feb 29 2028
28 29 30
Differences between dates
Subtracting two dates gives milliseconds. Converting that to calendar days by dividing by 86_400_000 breaks when the range crosses a DST change, so compare the calendar dates in UTC instead:
const a = new Date('2026-03-01T08:00:00Z');
const b = new Date('2026-03-04T20:30:00Z');
const ms = b - a; // Dates convert to numbers
console.log(ms);
console.log(ms / 3_600_000, 'hours');
function breakdown(ms) {
const s = Math.floor(ms / 1000);
return { days: Math.floor(s / 86400), hours: Math.floor(s / 3600) % 24, minutes: Math.floor(s / 60) % 60 };
}
console.log(breakdown(ms));
// calendar days between two local dates, DST-safe
function daysBetween(from, to) {
const utcFrom = Date.UTC(from.getFullYear(), from.getMonth(), from.getDate());
const utcTo = Date.UTC(to.getFullYear(), to.getMonth(), to.getDate());
return Math.round((utcTo - utcFrom) / 86_400_000);
}
const x = new Date(2026, 2, 1);
const y = new Date(2026, 2, 15);
console.log((y - x) / 86_400_000); // 23-hour day inside the range
console.log(daysBetween(x, y));
function age(birth, today = new Date()) {
let years = today.getFullYear() - birth.getFullYear();
const hadBirthday =
today.getMonth() > birth.getMonth() ||
(today.getMonth() === birth.getMonth() && today.getDate() >= birth.getDate());
if (!hadBirthday) years--;
return years;
}
console.log(age(new Date(1990, 9, 18), new Date(2026, 9, 17)));
console.log(age(new Date(1990, 9, 17), new Date(2026, 9, 17)));
304200000
84.5 hours
{ days: 3, hours: 12, minutes: 30 }
13.958333333333334
14
35
36
Relative times and durations
Intl.RelativeTimeFormat produces localized phrases like "yesterday" or "in 2 weeks". You choose the unit; a small helper picks the largest one that fits:
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtf.format(-1, 'day'), '|', rtf.format(2, 'week'), '|', rtf.format(-3, 'month'));
const units = [
['year', 365 * 24 * 3600],
['month', 30 * 24 * 3600],
['week', 7 * 24 * 3600],
['day', 24 * 3600],
['hour', 3600],
['minute', 60],
['second', 1],
];
function timeAgo(date, now = new Date(), locale = 'en') {
const fmt = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
const seconds = Math.round((date - now) / 1000);
for (const [unit, size] of units) {
if (Math.abs(seconds) >= size || unit === 'second') {
return fmt.format(Math.round(seconds / size), unit);
}
}
}
const now = new Date('2026-10-17T12:00:00Z');
console.log(timeAgo(new Date('2026-10-17T11:59:30Z'), now));
console.log(timeAgo(new Date('2026-10-17T09:00:00Z'), now));
console.log(timeAgo(new Date('2026-10-16T09:00:00Z'), now));
console.log(timeAgo(new Date('2026-12-01T00:00:00Z'), now));
console.log(timeAgo(new Date('2026-10-14T12:00:00Z'), now, 'es'));
const df = new Intl.DurationFormat('en', { style: 'long' });
console.log(df.format({ hours: 1, minutes: 46, seconds: 40 }));
console.log(new Intl.DurationFormat('en', { style: 'digital' }).format({ hours: 1, minutes: 6, seconds: 5 }));
yesterday | in 2 weeks | 3 months ago
30 seconds ago
3 hours ago
yesterday
next month
hace 3 días
1 hour, 46 minutes, 40 seconds
1:06:05
numeric: 'auto' gives "yesterday" and "next month"; the default 'always' gives "1 day ago" and "in 1 month". Intl.DurationFormat is available since Node.js 23.
Measuring elapsed time
Date.now() follows the system clock, which can be adjusted by NTP or by an administrator, and it only has millisecond resolution. For measuring how long something takes, use a monotonic clock:
import { performance } from 'node:perf_hooks';
import { setTimeout as sleep } from 'node:timers/promises';
const t0 = performance.now();
await sleep(50);
const t1 = performance.now();
console.log(`slept ${(t1 - t0).toFixed(1)} ms`);
const start = process.hrtime.bigint();
let sum = 0;
for (let i = 0; i < 1e6; i++) sum += i;
const ns = process.hrtime.bigint() - start;
console.log(typeof ns, ns > 0n);
slept 59.8 ms
bigint true
performance.now() returns fractional milliseconds since the process started; process.hrtime.bigint() returns nanoseconds as a BigInt. Neither is related to the calendar, so they can't be converted to a date. Timers are never early but may fire late, as the 59.8 ms above shows. For more about timers see setTimeout promisified.
Dates in JSON
JSON.stringify() calls toJSON(), which produces an ISO string. JSON.parse() has no way to know that a string was a date, so it stays a string unless you revive it:
const event = { name: 'launch', at: new Date('2026-07-04T18:00:00Z') };
const json = JSON.stringify(event);
console.log(json);
const back = JSON.parse(json);
console.log(typeof back.at, back.at instanceof Date);
const isoRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
const revived = JSON.parse(json, (key, value) =>
typeof value === 'string' && isoRe.test(value) ? new Date(value) : value);
console.log(revived.at instanceof Date, revived.at.getUTCFullYear());
// Unix timestamps (seconds) used by many APIs and JWTs
const unixSeconds = Math.floor(Date.now() / 1000);
console.log(Number.isInteger(unixSeconds));
console.log(new Date(1_783_188_000 * 1000).toISOString());
{"name":"launch","at":"2026-07-04T18:00:00.000Z"}
string false
true 2026
true
2026-07-04T18:00:00.000Z
Many APIs (JWT exp, Unix tools, some databases) use seconds, not milliseconds. Multiply or divide by 1000 at the boundary and name variables so the unit is obvious.
Temporal: the modern API
Temporal is the replacement for Date standardized in TC39. It has separate immutable types for different concepts: Instant (an exact moment), PlainDate (a calendar date with no time or zone), PlainDateTime, ZonedDateTime (a moment in a named time zone) and Duration. In Node.js 24 it is still experimental and must be enabled with a V8 flag; check typeof Temporal on your version, and use the temporal-polyfill package where it isn't available.
const instant = Temporal.Instant.from('2026-07-04T18:00:00Z');
console.log(instant.toString(), instant.epochMilliseconds);
const date = Temporal.PlainDate.from('2026-01-31');
console.log(date.add({ months: 1 }).toString()); // clamped to Feb 28
console.log(date.add({ days: 30 }).toString());
console.log(date.dayOfWeek, date.daysInMonth, date.inLeapYear);
const meeting = Temporal.ZonedDateTime.from('2026-03-07T12:00[America/New_York]');
console.log(meeting.add({ days: 1 }).toString()); // same wall-clock time
console.log(meeting.add({ hours: 24 }).toString()); // exactly 24 hours later
console.log(meeting.withTimeZone('Europe/Paris').toString());
const a = Temporal.PlainDate.from('2026-03-01');
const b = Temporal.PlainDate.from('2026-12-25');
console.log(a.until(b).toString(), a.until(b, { largestUnit: 'months' }).toString());
console.log(Temporal.PlainDate.compare(a, b));
const d = Temporal.Duration.from({ hours: 1, minutes: 90 });
console.log(d.toString(), d.round({ largestUnit: 'hours' }).toString());
// convert between Temporal and Date
const legacy = new Date(meeting.epochMilliseconds);
console.log(legacy.toISOString());
console.log(legacy.toTemporalInstant().toString());
$ node --harmony-temporal temporal.mjs
2026-07-04T18:00:00Z 1783188000000
2026-02-28
2026-03-02
6 31 false
2026-03-08T12:00:00-04:00[America/New_York]
2026-03-08T13:00:00-04:00[America/New_York]
2026-03-07T18:00:00+01:00[Europe/Paris]
P299D P9M24D
-1
PT1H90M PT2H30M
2026-03-07T17:00:00.000Z
2026-03-07T17:00:00Z
Everything that needed a hand-written helper with Date (clamping months, DST-aware day arithmetic, calendar differences, converting between zones) is built in. Months are 1-based, dayOfWeek is 1 (Monday) to 7 (Sunday), and every operation returns a new object.
Libraries
Until Temporal is enabled by default, a small library saves you from writing and testing the helpers above. date-fns is a collection of pure functions that take and return plain Date objects, and @date-fns/tz adds time zone support:
$ npm install date-fns @date-fns/tz
import { addMonths, differenceInCalendarDays, format, formatDistance, parse, isValid } from 'date-fns';
import { TZDate } from '@date-fns/tz';
const jan31 = new Date(2026, 0, 31);
console.log(format(addMonths(jan31, 1), 'yyyy-MM-dd'));
console.log(differenceInCalendarDays(new Date(2026, 2, 15), new Date(2026, 2, 1)));
console.log(format(new Date(2026, 6, 4, 14, 5), "EEEE, MMMM do yyyy 'at' HH:mm"));
console.log(formatDistance(new Date(2026, 0, 1), new Date(2026, 0, 3, 5), { addSuffix: true }));
const parsed = parse('15/03/2026', 'dd/MM/yyyy', new Date());
console.log(isValid(parsed), format(parsed, 'yyyy-MM-dd'));
console.log(isValid(parse('31/02/2026', 'dd/MM/yyyy', new Date())));
const tokyo = new TZDate(2026, 6, 4, 9, 0, 'Asia/Tokyo');
console.log(tokyo.toISOString());
console.log(format(tokyo, 'yyyy-MM-dd HH:mm zzz'));
2026-02-28
14
Saturday, July 4th 2026 at 14:05
2 days ago
true 2026-03-15
false
2026-07-04T09:00:00.000+09:00
2026-07-04 09:00 GMT+9
Unlike new Date(), date-fns' parse() follows an explicit format and rejects February 31. Other options are Luxon (immutable DateTime objects with time zones) and Day.js (small, Moment-like API). Moment.js itself is in maintenance mode and shouldn't be used in new code.
Summary
- A
Dateis a UTC millisecond timestamp; "local" methods interpret it in the process'sTZ. - Months in
new Date(y, m, d)andgetMonth()are 0-based. - Store and transmit timestamps as ISO 8601 strings with
Z(toISOString()), store user zones as IANA names. - Validate parsed dates with
Number.isNaN(d.getTime()); don't rely onDateto parse arbitrary formats. - Copy before calling
set*(); compare withgetTime()or<, never===. - Show times to users with
Intl.DateTimeFormatand an explicittimeZone; reuse formatters. - Use milliseconds for exact durations and
setDate()/setMonth()for calendar arithmetic; watch for DST and month-end overflow. - Measure elapsed time with
performance.now()orprocess.hrtime.bigint(), notDate.now(). - Look at
Temporalfor new code where it's available, or use date-fns or Luxon.