JavaScript Dates: the Date Object, Timestamps, Time Zones, Date Arithmetic and Formatting
How Date really works: one millisecond timestamp, creating dates, the 0-based month trap, local vs UTC getters, why date-only strings parse as UTC, invalid dates, overflow, date arithmetic and DST, comparing and copying, ISO strings and JSON, locale formatting, and when to reach for Temporal.
kvi5hnuCode Sprout team member7 min readOn this page
Dates are a famous source of bugs in every language, and JavaScript's Date object, designed in 1995 and copied from Java's first date class, has more surprises than most. Once you understand what a Date actually stores, though, almost every surprise becomes predictable. This article covers Date thoroughly, because it's in nearly all existing code. The next article covers Temporal, the modern replacement now arriving in browsers.
What a Date really is
A Date holds one number: the count of milliseconds since 1970-01-01T00:00 (the Unix epoch, in UTC). That's it. It doesn't store a time zone, a calendar or a format. It's an instant, a single point on the universal timeline.
const launch = new Date(Date.UTC(2026, 10, 18, 9, 30));
console.log(launch.getTime(), launch.valueOf() === +launch);
console.log(launch.toISOString());
console.log(new Date(0).toISOString(), new Date(-86_400_000).toISOString());
console.log(typeof Date.now());
1794994200000 true
2026-11-18T09:30:00.000Z
1970-01-01T00:00:00.000Z 1969-12-31T00:00:00.000Z
number
getTime()(orvalueOf(), or unary+) gives the timestamp.- Negative timestamps are dates before 1970.
Date.now()returns the current timestamp as a number, without creating an object, which is ideal for measuring elapsed time and for IDs. (For precise performance timing, useperformance.now().)
Everything that looks like a time zone, such as "Nov 18, 04" in New York or "15" in Kolkata, is just the same instant displayed for a particular zone:

Creating dates
new Date(); // now
new Date(1794994200000); // from a timestamp (ms)
new Date("2026-11-18T09:30:00Z"); // from an ISO 8601 string
new Date(2026, 10, 18, 9, 30); // from LOCAL components
new Date(Date.UTC(2026, 10, 18, 9, 30)); // from UTC components
new Date(otherDate); // a copy
Months start at 0
In the component forms, months are 0-based (0 = January, 11 = December), while days of the month start at 1:
const christmas = new Date(Date.UTC(2026, 11, 25));
console.log(christmas.toISOString().slice(0, 10), christmas.getUTCMonth());
console.log(new Date(Date.UTC(2026, 12, 1)).toISOString().slice(0, 10)); // month 12 = next January
2026-12-25 11
2027-01-01
getDay() (day of the week) is also 0-based, starting from Sunday = 0. Out-of-range components roll over instead of failing: month 12 becomes January of the next year, and February 30 becomes early March. That rollover is handy for arithmetic but hides typos.
Parsing strings: the UTC/local trap
Only ISO 8601 strings (YYYY-MM-DDTHH:mm:ss.sssZ and its shorter forms) parse reliably everywhere. Other formats like "11/18/2026" or "Nov 18 2026" are implementation-defined. And ISO strings have one notorious rule:
- A date-only string (
"2026-11-18") is parsed as UTC midnight. - A date-time string without an offset (
"2026-11-18T00:00") is parsed as local time.
console.log(new Date("2026-11-18").toISOString());
console.log(new Date("2026-11-18T09:30:00+05:30").toISOString());
2026-11-18T00:00:00.000Z
2026-11-18T04:00:00.000Z
So for a user in Los Angeles (UTC-8), new Date("2026-11-18").getDate() returns 17: UTC midnight is still the previous evening locally. When you mean a calendar date, parse it into local components yourself (new Date(2026, 10, 18)), keep it as a string, or use Temporal.PlainDate (next article). When you mean an instant, always include Z or an offset.
Invalid dates
An unparseable value gives an Invalid Date, an object whose timestamp is NaN:
const bad = new Date("31/12/2026");
console.log(bad.getTime(), String(bad), Number.isNaN(bad.getTime()));
try {
bad.toISOString();
} catch (err) {
console.log(err.name);
}
NaN Invalid Date true
RangeError
Check Number.isNaN(date.getTime()) after parsing user input. toISOString() throws on invalid dates, so a single bad value can crash JSON serialization.
Getting and setting components
Every component has a local getter/setter and a UTC one:
| Local | UTC | Returns |
|---|---|---|
getFullYear() | getUTCFullYear() | 2026 |
getMonth() | getUTCMonth() | 0 to 11 |
getDate() | getUTCDate() | 1 to 31 |
getDay() | getUTCDay() | 0 (Sunday) to 6 |
getHours(), getMinutes(), getSeconds(), getMilliseconds() | getUTC... |
Local methods use the time zone of the computer running the code, which differs between your laptop, your users and your server (often UTC). Code that uses local methods can pass on your machine and fail in production. Never use the old getYear(), which returns the year minus 1900.
Setters mutate the Date and roll over automatically:
const due = new Date(Date.UTC(2026, 10, 18));
const later = new Date(due); // copy first!
later.setUTCDate(later.getUTCDate() + 45); // 45 days later, across months and years
console.log(due.toISOString().slice(0, 10), later.toISOString().slice(0, 10));
const endOfJan = new Date(Date.UTC(2026, 0, 31));
endOfJan.setUTCMonth(1); // "February 31" rolls into March
console.log(endOfJan.toISOString().slice(0, 10));
2026-11-18 2027-01-02
2026-03-03
The second example is a classic bug: "add one month" from January 31 gives March 3, not the end of February. Libraries and Temporal clamp to the last valid day instead.
Date arithmetic and comparison
Subtracting Dates converts them to timestamps, giving the difference in milliseconds:
const DAY = 24 * 60 * 60 * 1000;
const today = new Date(Date.UTC(2026, 10, 18));
const holiday = new Date(Date.UTC(2026, 11, 25));
console.log((holiday - today) / DAY, today < holiday);
const copy = new Date(today);
console.log(copy == today, copy.getTime() === today.getTime());
37 true
false true
<,>,-work (they convert to numbers), but==and===compare object identity, so two equal Dates aren't==. ComparegetTime()values.- Adding a fixed number of milliseconds per day is fine for UTC instants, but in local time not every day has 24 hours: days when daylight saving time starts or ends have 23 or 25. For "same time tomorrow, local", use
setDate(getDate() + 1), which keeps the clock time. - Sort dates with
dates.sort((a, b) => a - b).
Converting to strings
const d = new Date(Date.UTC(2026, 10, 18, 9, 30));
console.log(d.toISOString());
console.log(d.toJSON(), JSON.stringify({ at: d }));
const parsedBack = new Date(JSON.parse(JSON.stringify({ at: d })).at);
console.log(parsedBack.getTime() === d.getTime(), typeof JSON.parse('{"at":"2026-11-18T09:30:00.000Z"}').at);
2026-11-18T09:30:00.000Z
2026-11-18T09:30:00.000Z {"at":"2026-11-18T09:30:00.000Z"}
true string
toISOString()gives an unambiguous UTC string, ideal for storage, APIs and logs.JSON.stringifyuses it automatically viatoJSON.JSON.parsedoes not turn it back into a Date; you get a string. Convert explicitly, or use a reviver (article 50).toString(),toDateString()andtoUTCString()give human-ish English formats that you shouldn't parse or show to users.
Formatting for people
For display, use the locale-aware methods, which are backed by Intl.DateTimeFormat (article 85):
const d = new Date(Date.UTC(2026, 10, 18, 9, 30));
d.toLocaleString("en-US", { timeZone: "America/New_York" }); // "11/18/2026, 4:30:00 AM"
d.toLocaleString("en-GB", { timeZone: "Asia/Kolkata" }); // "18/11/2026, 15:00:00"
d.toLocaleDateString("de-DE", { dateStyle: "full", timeZone: "UTC" }); // "Mittwoch, 18. November 2026"
const fmt = new Intl.DateTimeFormat("en-US", {
timeZone: "Asia/Tokyo", dateStyle: "medium", timeStyle: "short",
});
fmt.format(d); // "Nov 18, 2026, 6:30 PM"
The timeZone option is the right way to show an instant in a particular zone. Exact output can vary slightly between browsers and versions, so never parse these strings back, and don't hard-code them in tests.
Date best practices
- Store and transmit instants as ISO strings with
Z(or timestamps), and convert to a zone only for display. - Always copy before using setters (
new Date(d)), since Dates are mutable. - Avoid parsing anything but ISO strings, and remember that date-only ISO strings are UTC.
- Use UTC methods for calculations on instants; use local methods only when you deliberately mean "the user's local calendar".
- Validate with
Number.isNaN(date.getTime()). - For calendar dates without times (birthdays, due dates), wall-clock times, durations, or zone-aware arithmetic, prefer Temporal (next article) or a well-tested library such as date-fns or Luxon.
Common questions
Why is my date one day off?
Almost always a time zone issue: a date-only string like "2026-11-18" was parsed as UTC midnight and then displayed in a zone west of UTC, where it's still the previous day. Parse calendar dates as local components or use Temporal.PlainDate.
How do I get the number of days in a month?
Ask for day 0 of the following month, which rolls back to the last day of this month: new Date(Date.UTC(year, month + 1, 0)).getUTCDate(). Here month is 0-based.
How do I check whether two dates are the same day?
Compare the year, month and day in the same time zone, for example a.toISOString().slice(0, 10) === b.toISOString().slice(0, 10) for UTC days, or compare getFullYear(), getMonth() and getDate() for local days.
What's the range of a Date?
±8.64 × 10¹⁵ milliseconds from the epoch (about ±273,000 years). Beyond that you get an Invalid Date.
Summary
- A
Datestores one UTC timestamp in milliseconds since 1970; time zones only affect display and local getters. - Months (and weekdays) are 0-based; out-of-range components roll over.
- Only ISO strings parse reliably; date-only ISO strings are UTC, date-times without offsets are local.
- Invalid Dates have a
NaNtimestamp, andtoISOString()throws on them. - Getters and setters come in local and UTC versions; setters mutate, so copy first.
- Subtract dates for millisecond differences; compare with
getTime(), not===; beware DST in local arithmetic. - Use
toISOString()for data andtoLocaleString/Intl.DateTimeFormatwith atimeZonefor people.
Practice Questions
What does this code give, and why?
new Date(Date.UTC(2026, 1, 29)).toISOString().slice(0, 10)
Answer
"2026-03-01". 2026 isn't a leap year, so February 29 rolls over to March 1. Months are 0-based, so 1 is February.
Why is this code false?
new Date(2026, 0, 1) === new Date(2026, 0, 1)
Answer
They're two different objects, and === compares object identity. Compare their timestamps: a.getTime() === b.getTime().
Write a function that returns how many whole days remain until a given ISO date string (UTC), from now.
Answer
const daysUntil = (iso) => Math.ceil((new Date(iso) - Date.now()) / 86_400_000);
Why should a server log toISOString() rather than toString()?
Answer
toISOString() is unambiguous (UTC, fixed format), sorts correctly as text and parses reliably everywhere. toString() depends on the server's time zone and isn't a standard parseable format.
Next: Temporal in JavaScript: PlainDate, ZonedDateTime, Instant, Durations and Replacing Date

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.