The built-in Date object represents a single moment in time. The API is older and quirkier than most of the language, so a little care helps.
Creating a date
const now = new Date(); // the current moment
const fromString = new Date("2026-03-15T10:30:00Z");
const fromParts = new Date(2026, 2, 15, 10, 30); // year, month, day, hours, minutes
const fromTimestamp = new Date(0); // milliseconds since 1 Jan 1970 UTC
console.log(fromString.toISOString()); // → 2026-03-15T10:30:00.000Z
console.log(fromTimestamp.toISOString()); // → 1970-01-01T00:00:00.000Z
console.log(typeof now); // → object
The month trap
When you pass numbers, months start at 0: January is 0, December is 11. Days of the month start at 1.
const march = new Date(2026, 2, 15); // 2 means March!
console.log(march.getMonth()); // → 2
console.log(march.getDate()); // → 15
This is a classic bug source. If your date is “one month off”, this is why.
Invalid dates
const bad = new Date("not a date");
console.log(bad.toString()); // → Invalid Date
console.log(Number.isNaN(bad.getTime())); // → true
A Date never throws for bad input. It becomes an “Invalid Date” whose time value is NaN, so check with Number.isNaN(date.getTime()).
How strings are parsed
Stick to the ISO 8601 format, YYYY-MM-DDTHH:mm:ss, which is reliably understood.
console.log(new Date("2026-03-15T10:30:00Z").toISOString()); // → 2026-03-15T10:30:00.000Z (Z = UTC)
console.log(new Date("2026-03-15T10:30:00+05:30").toISOString()); // → 2026-03-15T05:00:00.000Z
Two behaviours to know:
- A date-only string such as
"2026-03-15"is treated as UTC midnight. - A date and time without a zone, such as
"2026-03-15T10:30", is treated as local time.
That difference is the source of many “off by one day” bugs. Other formats like "March 15, 2026" or "15/03/2026" are not reliable across browsers. Avoid them.
Copying a date
const a = new Date("2026-01-01T00:00:00Z");
const b = new Date(a); // a copy, not the same object
b.setUTCFullYear(2030);
console.log(a.getUTCFullYear()); // → 2026
Dates are objects, so assigning const b = a would share the same one.
A newer API exists
Date. Browser support is still arriving, so check support tables before using it in a project. This course uses Date and Intl, which work everywhere.