Sub topic 2
Creating Dates and the Zero-Based Month Trap
This chapter assumes you know JavaScript fundamentals and can run code in a browser console or Node.js. It also assumes the idea from the previous chapter: a Date holds a single number, the milliseconds since 1970-01-01T00:00:00Z. Every way of creating a Date is a way of working out that number. The rules for each way differ, and most bugs come from the differences.
The Constructor Forms at a Glance
The Date constructor decides what to do from the number and type of its arguments.
| Call | What the arguments mean | Interpreted in |
|---|---|---|
| `new Date()` | The current moment | Not applicable |
| `new Date(ms)` | Milliseconds since the epoch | UTC (no zone involved) |
| `new Date(otherDate)` | Copy the time value of another `Date` | Not applicable |
| `new Date(string)` | Parse the text (covered in the next chapter) | Depends on the string |
| `new Date(y, m, d?, h?, min?, s?, ms?)` | Calendar components, `m` zero-based | Local time zone |
| `Date.UTC(y, m?, d?, ...)` | Calendar components, `m` zero-based; returns a number | UTC |
| `Date()` without `new` | Ignores all arguments; returns a string | Not applicable |
Timestamps, Copies, and the Current Time
const now = new Date(); // same instant as Date.now()
const epochPlusDay = new Date(86400000); // 1970-01-02T00:00:00.000Z
const copy = new Date(now); // independent object, same instant
console.log(epochPlusDay.toISOString()); // "1970-01-02T00:00:00.000Z"
console.log(copy.getTime() === now.getTime()); // true
console.log(copy === now); // false: two separate objects
console.log(typeof Date()); // "string"
console.log(typeof new Date()); // "object"A timestamp argument has no time zone. It names an instant directly, so new Date(86400000) is the same moment on every machine. Use this form when the input comes from a database, an API, or Date.now().
Copying with new Date(original) is the standard way to protect a date before you change it, because setters modify the object in place. Older code sometimes writes new Date(original.getTime()). That does the same thing and still appears in many codebases.
Building a Date from Components
With two or more arguments, the constructor reads them as year, month, day, hours, minutes, seconds, and milliseconds, in the local time zone of the machine running the code. Any arguments you leave out default to the start of the period: day 1 and zero for every time field.
const launch = new Date(2024, 6, 4, 9, 30); // July 4, 2024, 09:30 local time
console.log(launch.getFullYear()); // 2024
console.log(launch.getMonth()); // 6 (July)
console.log(launch.getDate()); // 4
console.log(launch.getHours()); // 9Because the components are read as local time, this code creates a different instant in Tokyo than in London. Both machines show "09:30 on July 4" in their local getters, but launch.getTime() gives different values. If you need components fixed to UTC, use Date.UTC:
const ms = Date.UTC(2024, 6, 4, 9, 30); // a number, not a Date
const launchUTC = new Date(ms);
console.log(launchUTC.toISOString()); // "2024-07-04T09:30:00.000Z" everywhereDate.UTC returns a time value. Wrap it in new Date(...) when you need an object.
The One-Argument Year Trap
You need at least two arguments to get component mode. A single number is always read as milliseconds:
console.log(new Date(2024).toISOString()); // "1970-01-01T00:00:02.024Z"
console.log(new Date(2024, 0).getFullYear()); // 2024Date.UTC(2024) is an exception. Since ES2017 its month argument is optional, so it returns midnight UTC on January 1, 2024. The constructor and Date.UTC behave differently here, which is one more reason to always pass the month explicitly.
The Zero-Based Month
Months run from 0 (January) to 11 (December). Days of the month run from 1 to 31. This mismatch comes from Java's 1995 java.util.Date, which JavaScript copied. It is the most common date bug in JavaScript.
const wrong = new Date(2024, 12, 25); // intended: December 25, 2024
console.log(wrong.getFullYear(), wrong.getMonth(), wrong.getDate()); // 2025 0 25
const right = new Date(2024, 11, 25);
console.log(right.getFullYear(), right.getMonth(), right.getDate()); // 2024 11 25Off-by-one month errors are easy to miss because they never throw. Three habits help:
- Convert human month numbers at the boundary only:
new Date(year, month - 1, day), and add 1 back when you displaygetMonth(). - Give month indexes names, such as
const JUNE = 5, in code that hard-codes dates. - Watch the related getter names.
getDate()returns the day of the month (1 to 31).getDay()returns the weekday, from 0 for Sunday to 6 for Saturday.
Overflow and Rollover
The constructor does not check ranges. Any field outside its normal range spills into the next larger unit, and negative values or zero borrow from it:
const show = (d) => `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
console.log(show(new Date(2024, 0, 32))); // "2024-2-1" Jan 32 -> Feb 1
console.log(show(new Date(2024, 12, 1))); // "2025-1-1" month 12 -> next January
console.log(show(new Date(2024, -1, 1))); // "2023-12-1" month -1 -> previous December
console.log(show(new Date(2024, 2, 0))); // "2024-2-29" day 0 -> last day of February
console.log(show(new Date(2024, 0, 1, 25))); // "2024-1-2" hour 25 -> next day, 01:00Rollover causes bugs when the input is wrong, but you can also use it on purpose. Day 0 of a month is the last day of the month before it, which gives a short way to count the days in a month:
// month is zero-based, like the Date API
function daysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
console.log(daysInMonth(2024, 1)); // 29 (leap year February)
console.log(daysInMonth(2023, 1)); // 28
console.log(daysInMonth(2024, 11)); // 31Validating User-Supplied Components
Rollover means new Date(2023, 1, 30) quietly becomes March 2 and does not fail. To reject impossible dates, build the date and check that the components come back unchanged:
// Takes a human (1-based) month and returns a Date or null.
function makeLocalDate(year, month, day) {
const d = new Date(year, month - 1, day);
const valid =
d.getFullYear() === year &&
d.getMonth() === month - 1 &&
d.getDate() === day;
return valid ? d : null;
}
console.log(makeLocalDate(2024, 2, 29) !== null); // true
console.log(makeLocalDate(2023, 2, 29)); // null: 2023 is not a leap year
console.log(makeLocalDate(2024, 13, 1)); // nullTwo-Digit Years and the Valid Range
When the year argument is between 0 and 99, both the constructor and Date.UTC add 1900 to it. This is a leftover from the 1990s:
console.log(new Date(99, 0, 1).getFullYear()); // 1999
console.log(new Date(5, 0, 1).getFullYear()); // 1905
const year5 = new Date(2000, 0, 1);
year5.setFullYear(5); // setFullYear has no such mapping
console.log(year5.getFullYear()); // 5If your app handles historical years, set the year with setFullYear after construction. Also avoid the deprecated getYear(), which returns the year minus 1900.
A time value must lie within ±8.64 × 10¹⁵ milliseconds of the epoch, which is 100,000,000 days either way. Anything outside that range, and any NaN input, produces an Invalid Date. An Invalid Date is a Date object whose time value is NaN:
const tooFar = new Date(8.64e15 + 1);
const garbage = new Date(2024, NaN);
console.log(Number.isNaN(tooFar.getTime())); // true
console.log(Number.isNaN(garbage.getTime())); // true
console.log(String(garbage)); // "Invalid Date"An Invalid Date is still truthy and still instanceof Date, so checks like if (date) do not catch it. Test Number.isNaN(date.getTime()). Calling toISOString() on an Invalid Date throws a RangeError, and that error often surfaces far from the code that created the bad date.
Exercise
A form sends year 2024, month 9, day 31 using human month numbers. The code runs new Date(2024, 9, 31). What date does getMonth() and getDate() report, and what should the call have been?
Show answer
Month index 9 is October, and October has 31 days, so the date is valid but wrong: getMonth() returns 9 and getDate() returns 31, which is October 31. The user meant September 31, which does not exist. The correct call is new Date(2024, 9 - 1, 31). That call rolls over to October 1 (getMonth() 9, getDate() 1), and a round-trip check like makeLocalDate would reject it.
Exercise
Why does new Date(1700000000000) give a sensible 2023 date while new Date(2023) gives a moment in January 1970? How would you write the start of 2023 in UTC?
Show answer
With a single numeric argument the constructor always reads the value as epoch milliseconds. 1700000000000 ms falls in November 2023, while 2023 ms is about two seconds after the epoch. For January 1, 2023 at midnight UTC, write new Date(Date.UTC(2023, 0, 1)).
Exercise
Use rollover to write a function lastDayOfMonth(date) that returns a new Date for the last day of the month containing date, in local time, without changing the argument.
Show answer
function lastDayOfMonth(date) { return new Date(date.getFullYear(), date.getMonth() + 1, 0); } Day 0 of the next month is the last day of the current month. The function builds a new object, so the argument is not changed. December works too, because month 12 rolls over into January of the next year and day 0 then steps back to December 31.