Sub topic 1
What a Date Really Is: One Instant in Milliseconds
Prerequisites
This chapter assumes you know JavaScript basics: variables, functions, and objects. It also assumes you can run code in a browser console or Node.js, and that you have a rough idea of what UTC and time zones are.
One Number Underneath
A Date stores a single number. That number is the count of milliseconds since the Unix epoch, which is 1970-01-01T00:00:00Z. The year, the hour and the weekday are all calculated from it. This is also why subtracting one date from another gives you milliseconds.
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)Creating Dates and the Zero-Based Month Trap
When you build a date from components, the values are read in local time. Months run from 0 to 11. If a value is out of range, JavaScript does not throw an error. It rolls the extra days into the next month.
const d = new Date(2024, 0, 31); // January 31, 2024
d.setMonth(1); // ask for "February 31"
console.log(d.getMonth(), d.getDate()); // 2 2 -> March 2Parsing Strings: Use ISO 8601
ISO 8601 strings parse the same way in every engine, with one quirk. A date-only string is read as UTC. A date-time string with no offset is read as local time.
const dateOnly = new Date("2024-03-10"); // UTC midnight
const dateTime = new Date("2024-03-10T00:00"); // local midnight
const withZ = new Date("2024-03-10T00:00Z"); // explicit UTC
console.log(dateOnly.getTime() === withZ.getTime()); // true
console.log(new Date("not a date").getTime()); // NaNLocal Time and UTC: Two Views
Each getter and setter comes in two forms. getHours reads the time in the runtime's local zone. getUTCHours reads it in UTC. Both forms read the same stored instant.
| Local | UTC |
|---|---|
| `getHours()` | `getUTCHours()` |
| `setDate()` | `setUTCDate()` |
Comparing, Copying, and Arithmetic
Compare dates with getTime(). The == and === operators compare object references, not instants. Setters change the date in place, so copy the date before you change it.
function addDaysUTC(date, days) {
const result = new Date(date.getTime());
result.setUTCDate(result.getUTCDate() + days);
return result;
}
const start = new Date("2024-03-09T12:00:00Z");
const next = addDaysUTC(start, 1);
console.log(next.toISOString()); // "2024-03-10T12:00:00.000Z"
console.log(start.getTime() === next.getTime()); // falseExercise
What do getMonth() and getDate() return for new Date(2024, 1, 30), and why?
Show answer
They return 2 and 1, which is March 1, 2024. Month 1 is February, and February 2024 has 29 days, so day 30 rolls over into March.