Sub topic 1
What a Date Really Is: One Instant in Milliseconds
A JavaScript Date holds no year, month, day, hour, or time zone. It holds one number: the count of milliseconds since midnight UTC on January 1, 1970, a moment called the Unix epoch. Every method on a Date reads or rewrites that number. Once you see a Date this way, most of its odd behavior makes sense, and the later chapters on time zones, arithmetic, and formatting all build on this model.
Prerequisites
This chapter assumes you can:
- Write JavaScript with variables, functions, objects, and arrays.
- Run code in a browser console or with Node.js.
- Explain in rough terms what UTC is and why time zones exist.
You don't need to know anything about the Date API yet.
The time value
The ECMAScript specification calls the stored number the time value. It is a plain JavaScript number with these properties:
- It is a whole number of milliseconds. Fractions are dropped.
- Positive values are after the epoch, and negative values are before it.
- Zero is exactly
1970-01-01T00:00:00.000Z. - If the date is invalid, the time value is
NaN.
const now = Date.now(); // milliseconds since 1970-01-01T00:00:00Z
const d = new Date(0);
console.log(d.toISOString()); // "1970-01-01T00:00:00.000Z"
console.log(d.getTime()); // 0
const a = new Date(2024, 0, 1);
const b = new Date(2024, 0, 2);
console.log(b - a); // 86400000 (one day, unless a DST change falls in between)Date.now() returns the current time value directly, without creating an object. getTime() reads the time value out of an existing Date. Subtracting one Date from another subtracts their time values, so the result is a duration in milliseconds.
An instant with no time zone
A time value names a single instant, the same moment everywhere on Earth. Time zones only come into play when you ask a Date to turn that number into calendar fields such as "July 4, 12:30 PM". Methods like toISOString() and getUTCHours() compute the fields for UTC. Methods like getHours() and toString() compute them for the time zone of the machine running the code.
The code below creates one instant from a raw number and then reads it several ways:
const instant = new Date(1720110600000);
console.log(instant.getTime()); // 1720110600000 on every machine
console.log(instant.toISOString()); // "2024-07-04T16:30:00.000Z" on every machine
console.log(instant.getUTCHours()); // 16 on every machine
console.log(instant.getHours()); // depends on the runtime's time zone: 12 in New York, 1 in TokyoThe first three lines print the same output on every computer. The last line differs from one machine to another, yet the object is identical. The difference comes from the view you chose, and the data stays the same.
How a Date turns into a number
Because a Date wraps a number, JavaScript converts it to that number in numeric contexts. There are several ways to get the time value out:
const d = new Date(Date.UTC(2024, 0, 1));
console.log(d.getTime()); // 1704067200000
console.log(d.valueOf()); // 1704067200000
console.log(+d); // 1704067200000
console.log(Number(d)); // 1704067200000
console.log(d - 0); // 1704067200000
console.log(typeof (d + 1)); // "string" (the + operator turns a Date into a string)
console.log(d + 1); // e.g. "Mon Jan 01 2024 01:00:00 GMT+0100 (Central European Standard Time)1"The last two lines show a common error. For most objects, the + operator asks for a number first. For Date it asks for a string, so d + 1 concatenates text and does not add a millisecond. Subtraction, multiplication, and the comparison operators always ask for a number, which is why b - a works. When you need arithmetic, call getTime() explicitly so readers don't have to remember the conversion rules.
Comparing dates
The relational operators <, >, <=, and >= convert both sides to numbers, so they compare instants correctly. Equality operators behave differently: == and === compare object identity when both sides are objects.
const x = new Date("2024-07-04T16:30:00Z");
const y = new Date("2024-07-04T16:30:00Z");
console.log(x < y, x > y); // false false
console.log(x <= y && x >= y); // true (same instant)
console.log(x === y); // false (two different objects)
console.log(x.getTime() === y.getTime()); // true (compare the time values)To test whether two dates are equal, always compare their getTime() results.
The range and Invalid Date
The time value can range over ±8.64 × 10¹⁵ milliseconds, which is exactly 100,000,000 days on each side of the epoch. Any value outside that range, and any input that can't be read as a date, produces an Invalid Date: a real Date object whose time value is NaN.
console.log(new Date(8.64e15).toISOString()); // "+275760-09-13T00:00:00.000Z"
console.log(new Date(-8.64e15).toISOString()); // "-271821-04-20T00:00:00.000Z"
console.log(new Date(8.64e15 + 1).getTime()); // NaN
const bad = new Date("not a date");
console.log(bad instanceof Date); // true, it is still a Date object
console.log(Number.isNaN(bad.getTime())); // true, this is the reliable validity check
console.log(String(bad)); // "Invalid Date"
try {
bad.toISOString();
} catch (e) {
console.log(e.name); // "RangeError"
}
console.log(new Date(1.9).getTime()); // 1 (fractions are truncated)An Invalid Date fails quietly. Getters return NaN, toString() returns "Invalid Date", and toISOString() throws a RangeError. Validate dates at input boundaries with Number.isNaN(date.getTime()). An instanceof check won't catch an Invalid Date, because the object is still a Date.
Seconds versus milliseconds
Many other systems, including Unix shells, most databases, JWT exp claims, and many HTTP APIs, count seconds since the epoch. JavaScript counts milliseconds. If you mix the two units, the code doesn't throw an error. It silently returns the wrong date.
const unixSeconds = 1720110600; // from an API: seconds since the epoch
console.log(new Date(unixSeconds).toISOString()); // "1970-01-20T21:48:30.600Z" (wrong)
console.log(new Date(unixSeconds * 1000).toISOString()); // "2024-07-04T16:30:00.000Z" (right)
const backToSeconds = Math.floor(Date.now() / 1000); // JS time to Unix seconds
console.log(Number.isInteger(backToSeconds)); // trueIf a date lands in January 1970, suspect seconds passed where milliseconds were expected. A current timestamp in seconds has 10 digits. In milliseconds it has 13.
What the time value ignores
The time value model makes some simplifications:
| Aspect | How `Date` handles it | Consequence |
|---|---|---|
| Leap seconds | Ignored; every day is exactly 86,400,000 ms | Matches POSIX time; differences across leap seconds are off by up to a second |
| Precision | Whole milliseconds only | Microseconds and nanoseconds are lost |
| Clock source | System wall clock | `Date.now()` can jump backward if the clock is adjusted |
| Calendar | Proleptic Gregorian, extended back before 1582 | Historical dates in other calendars need conversion |
| Time zone | Not stored | Store the zone name separately if it matters |
The clock-source row matters for measuring how long something takes. Date.now() follows the system clock, and NTP sync or a manual change can move that clock. For elapsed time, use performance.now(), which is monotonic (it never goes backward) and gives sub-millisecond resolution. Some browsers also coarsen Date.now() on purpose to resist fingerprinting.
const t0 = performance.now();
for (let i = 0; i < 1e6; i++); // some work
const elapsed = performance.now() - t0;
console.log(`took ${elapsed.toFixed(2)} ms`);Common errors at a glance
- Writing
date1 === date2to test equality. ComparegetTime()values instead. - Writing
date + 1000to add a second. Usenew Date(date.getTime() + 1000). - Passing Unix seconds to
new Date(). Multiply by 1000 first. - Assuming a
Date"is in" a time zone. Only its views are. - Skipping the validity check. Test
Number.isNaN(date.getTime())after building a date from input.
Exercise
Two servers, one in Tokyo and one in London, each run new Date("2024-07-04T16:30:00Z").getTime() and .getHours(). Which of the two results match between the servers, and why?
Show answer
The getTime() results match: both are 1720110600000, because the string names one instant and the time value is the same everywhere. The getHours() results differ (1 in Tokyo, 17 in London during British Summer Time), because getHours computes the hour field in each runtime's local time zone.
Exercise
An API returns { "expires": 1735689600 }. A developer writes if (new Date(data.expires) < new Date()) logout();. What goes wrong, and how do you fix it?
Show answer
The value is in seconds, but new Date treats it as milliseconds, so the expiry date lands on 1970-01-21 and the check always logs the user out. Convert the units: if (data.expires * 1000 < Date.now()) logout();. Comparing numbers directly also avoids creating Date objects.
Exercise
Write a function isValidDate(value) that returns true only for Date objects holding a real instant. It must return false for Invalid Date and for values that aren't Dates.
Show answer
const isValidDate = (value) => value instanceof Date && !Number.isNaN(value.getTime()); The instanceof check rejects strings, numbers, and other non-Dates, and the NaN check rejects Invalid Date objects.