JavaScript Date Explained: Format, Parse and Avoid Timezone Bugs
The JavaScript Date object stores one moment in time, but zero-based months, local vs UTC methods and string parsing cause classic off-by-one bugs. Learn how Date really works, how to parse and format safely with Intl, and how to do date math, with output from tested Node.js runs.
- A JavaScript Date is a single number: milliseconds since 1 January 1970 UTC. Time zones only matter when you read or write it.
- Months run from 0 to 11.
new Date(2026, 10, 17)is 17 November. new Date("2026-11-17")is parsed as UTC midnight. In our New York test it displayed as 16 November.- Format for people with
toLocaleStringorIntl.DateTimeFormat, and for machines withtoISOString().
A user in New York picks 17 November on a form, and the confirmation page says 16 November. A report built at midnight lands in the wrong month. These bugs come from the JavaScript Date object, which is famous for surprising behaviour. Once you know how it stores time and which methods use which zone, the surprises go away.
We ran every example with Node.js 24.22.1. To make results repeatable, most runs set the process time zone to UTC with process.env.TZ. Where the zone matters, we ran the same code under New York and Kolkata time and show both.
What a Date actually stores
Internally a Date holds one number: the milliseconds since the Unix epoch, 1 January 1970 at 00:00 UTC. It has no time zone of its own. Methods such as getHours() translate that number into the local zone of the machine running the code, while getUTCHours() uses UTC. The same Date can therefore print differently on a server and in a browser. Our Unix timestamp guide explains the epoch in depth.
Creating dates
new Date() // now
new Date(1794873600000) // from milliseconds since the epoch
new Date("2026-11-17T09:30:00Z") // from an ISO string
new Date(2026, 10, 17, 9, 30) // from parts, in LOCAL time
new Date(Date.UTC(2026, 10, 17)) // from parts, in UTC
Date.now() returns the current time as a number of milliseconds, which is handy for timing. It is 13 digits long today, as our run confirmed. Date.UTC() also returns a number, so wrap it in new Date() when you need a Date object.
Zero-based months (and day overflow)
const d = new Date(2026, 10, 17, 9, 30);
console.log(d.toISOString(), d.getMonth(), d.getDay(), d.getDate());
// 2026-11-17T09:30:00.000Z 10 2 17
Month index 10 is November. getDay() returns the weekday (2 means Tuesday, with Sunday as 0), and getDate() returns the day of the month. Mixing up getDay and getDate is the second most common Date bug after months.
Out-of-range values do not raise errors. They roll over silently:
new Date(2026, 1, 30).toISOString().slice(0, 10)
// 2026-03-02
“30 February” became 2 March. That is useful for date math, but it means invalid user input will not be caught. Validate the parts yourself if you build dates from form fields.
The string parsing trap
This is the bug behind most “off by one day” reports. A date-only ISO string is treated as UTC, but a date-time string without a zone is treated as local. We ran the same line under two zones:
const d = new Date("2026-11-17");
console.log(d.getDate(), d.toString().slice(0, 15));
| Time zone | getDate() | Displayed | new Date(“2026-11-17T00:00”) |
|---|---|---|---|
| America/New_York | 16 | Mon Nov 16 2026 | 2026-11-17T05:00:00.000Z |
| Asia/Kolkata | 17 | Tue Nov 17 2026 | 2026-11-16T18:30:00.000Z |
In New York, UTC midnight on the 17th is still the evening of the 16th, so the local display shows the wrong day. Users west of Greenwich see the bug; developers east of it often never notice. The fixes:
- For a calendar date with no time, such as a birthday, keep it as the string
"2026-11-17"or build it withnew Date(2026, 10, 17)in local time. - For a moment in time, always include the zone:
"2026-11-17T09:30:00Z"or"...+05:30". - Never parse formats such as
"17/11/2026". Our run returnedNaNfor it, and other engines may guess differently.
Invalid dates
console.log(String(new Date("nope")), isNaN(new Date("nope")));
// Invalid Date true
A failed parse does not throw. It returns a Date whose time value is NaN. Check with isNaN(d) or Number.isNaN(d.getTime()) before using user-supplied dates. Calling toISOString() on an invalid date throws a RangeError, which often surfaces far from the original input.
Local vs UTC methods
Almost every getter and setter comes in two versions: getHours() and getUTCHours(), setDate() and setUTCDate(), and so on. Pick one family per task and stick with it. Server code that stores and compares times is usually simplest in UTC. Code that shows times to a person should format in their zone.
getTimezoneOffset and its backwards sign
new Date(2026, 10, 17).getTimezoneOffset()
// UTC: 0 America/New_York: 300 Asia/Kolkata: -330
The result is in minutes, and the sign is the reverse of how offsets are usually written. New York is UTC−5, yet the method returns +300. Kolkata is UTC+5:30 and returns −330. The value can also change during the year because of daylight saving, so always ask for the offset of the specific date you care about.
Formatting dates
For machines, use ISO 8601. toISOString() always outputs UTC with a Z:
new Date(Date.UTC(2026, 10, 17, 4, 0)).toISOString()
// 2026-11-17T04:00:00.000Z
For a custom fixed format, build it from parts and pad with padStart:
const pad = n => String(n).padStart(2, "0");
const f = new Date(Date.UTC(2026, 10, 7, 5, 4));
console.log(`${f.getUTCFullYear()}-${pad(f.getUTCMonth() + 1)}-${pad(f.getUTCDate())} ${pad(f.getUTCHours())}:${pad(f.getUTCMinutes())}`);
// 2026-11-07 05:04
Remember the + 1 on the month. Our JavaScript tutorial covers template literals if the syntax is new.
Formatting for people with Intl
For anything a person reads, let the built-in Intl API handle language, order and time zone:
const x = new Date(Date.UTC(2026, 10, 17, 4, 0));
x.toLocaleDateString("en-GB", { timeZone: "UTC" }) // 17/11/2026
x.toLocaleDateString("en-US", { timeZone: "UTC" }) // 11/17/2026
x.toLocaleString("en-IN", { timeZone: "Asia/Kolkata", dateStyle: "medium", timeStyle: "short" })
// 17 Nov 2026, 9:30 am
x.toLocaleString("en-US", { timeZone: "America/New_York", dateStyle: "full", timeStyle: "long" })
// Monday, November 16, 2026 at 11:00:00 PM EST
new Intl.DateTimeFormat("de-DE", { weekday: "long", day: "numeric", month: "long", timeZone: "UTC" }).format(x)
// Dienstag, 17. November
The same instant appears as Tuesday morning in India and Monday night in New York, correctly, because we named the zone. Always pass timeZone when the viewer’s zone is known. Intl.RelativeTimeFormat handles phrases: our run produced “yesterday” for -1, "day" with numeric: "auto", and “in 3 weeks” for 3, "week".
Date math
const a = new Date(Date.UTC(2026, 10, 17));
const b = new Date(Date.UTC(2026, 11, 25));
console.log((b - a) / 86400000); // 38 days
const e = new Date(Date.UTC(2026, 10, 17));
e.setUTCDate(e.getUTCDate() + 45);
console.log(e.toISOString().slice(0, 10)); // 2027-01-01
Subtracting Dates gives milliseconds; divide by 86,400,000 for days. Adding days with setUTCDate rolls across months and years correctly. Adding months needs care:
const c = new Date(Date.UTC(2026, 0, 31));
c.setUTCMonth(c.getUTCMonth() + 1);
console.log(c.toISOString().slice(0, 10)); // 2026-03-03
“31 January plus one month” overflowed past February into 3 March. Decide your business rule, usually “clamp to the last day of the month”, and code it explicitly. Doing day math in local time across a daylight saving change can also give 23 or 25 hour days, so prefer UTC methods for arithmetic.
Comparing dates
console.log(a < b, a == new Date(a), a.getTime() === new Date(a).getTime());
// true false true
< and > work because they convert Dates to numbers. But == and === compare object identity, so two Dates for the same instant are “not equal”. Compare getTime() values instead. In tests, assert on toISOString() strings for readable failure messages.
Dates are mutable
const shared = new Date(Date.UTC(2026, 10, 17));
const copy = shared;
copy.setUTCFullYear(2030);
console.log(shared.getUTCFullYear()); // 2030
Assignment does not copy a Date, and setters change it in place. A function that “adds a day” to a Date passed in will change the caller’s object too. Make a real copy with new Date(d) or new Date(d.getTime()) before modifying.
Dates in JSON
JSON.stringify({ at: x }) // {"at":"2026-11-17T04:00:00.000Z"}
typeof JSON.parse(JSON.stringify({ at: x })).at // 'string'
Dates serialise to ISO strings, but parsing does not turn them back into Dates. Convert known date fields with new Date(value) after JSON.parse, or use a reviver function. Our Fetch API guide shows where this comes up with API responses.
Temporal and date libraries
The Temporal API is a modern replacement with separate types for plain dates, zoned date-times and durations. It was undefined in our Node.js 24.22.1 run, so check your target runtimes before using it. Until it is everywhere, small libraries such as date-fns and Luxon cover formatting, parsing and time zones with clearer APIs. For simple needs, the built-in Date plus Intl, used carefully as above, is enough.
Final thoughts
The JavaScript Date is less mysterious once you see it as a single UTC timestamp with local and UTC views. Remember the zero-based months, never trust date-only strings for local dates, pass timeZone when formatting, do arithmetic with UTC methods, compare with getTime(), and copy before you mutate. Add a test that runs in a zone west of UTC, and the off-by-one-day bug will never reach your users.
FAQ
Why is my JavaScript date one day off?
A date-only string such as 2026-11-17 is parsed as UTC midnight. In time zones west of UTC that is still the previous day locally. Build local dates from parts instead.
Why does getMonth return the wrong month?
JavaScript months are zero-based, so January is 0 and December is 11. Add one when displaying the month number.
How do I format a date as YYYY-MM-DD in JavaScript?
Use toISOString and take the first ten characters for a UTC date, or build the string from getFullYear, getMonth plus one and getDate with padStart for a local date.
How do I compare two dates in JavaScript?
Use less than or greater than for ordering. For equality compare the getTime values, because double and triple equals compare object identity.
How do I get the current timestamp in JavaScript?
Date.now returns milliseconds since 1 January 1970 UTC. Divide by 1000 and round down if an API expects seconds.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.