Sub topic 3
Parsing Strings: Why ISO 8601 Is the Only Safe Format
This chapter assumes you know how to create a Date from components and that a Date stores one instant as milliseconds since the Unix epoch. It also assumes you have a rough idea of what UTC and local time mean. Local and UTC getters get their own chapter later.
What the specification actually guarantees
When you pass a string to new Date(string) or Date.parse(string), the engine tries to turn it into a time value. The ECMAScript specification requires only one format to work: a simplified form of ISO 8601, written as YYYY-MM-DDTHH:mm:ss.sssZ. Any other string is parsed in whatever way the engine chooses, which the spec calls "implementation-defined". So "03/10/2024", "10 March 2024", or "2024/03/10" can give different results in Chrome, Firefox, Safari, and Node.js, or fail completely.
The common error is to test a non-ISO string in one browser, see it work, and ship it.
The three ISO cases
Even within ISO 8601, the way the engine reads a string depends on which parts are present.
const dateOnly = new Date("2024-03-10"); // date-only: parsed as UTC midnight
const dateTime = new Date("2024-03-10T00:00"); // date-time, no offset: parsed as LOCAL midnight
const withZ = new Date("2024-03-10T00:00Z"); // explicit UTC
const withOff = new Date("2024-03-10T00:00+05:30"); // explicit offset
console.log(dateOnly.getTime() === withZ.getTime()); // true
console.log(withOff.toISOString()); // "2024-03-09T18:30:00.000Z"
console.log(dateTime.toISOString()); // depends on the machine's time zoneReading date-only strings as UTC is the most frequent source of "off by one day" bugs. In any zone west of UTC, such as the Americas, new Date("2024-03-10") displays as March 9 in local time.
Detecting failure
Parsing never throws an error. When the engine can't parse a string, it returns an Invalid Date, whose time value is NaN. Check for it on purpose:
function parseISO(text) {
const d = new Date(text);
if (Number.isNaN(d.getTime())) {
throw new RangeError(`Invalid date string: ${text}`);
}
return d;
}
console.log(parseISO("2024-03-10T12:00:00Z").toISOString()); // "2024-03-10T12:00:00.000Z"
try {
parseISO("not a date");
} catch (e) {
console.log(e.message); // "Invalid date string: not a date"
}Parsing a calendar date as local
If a string such as "2024-03-10" means "this day on the user's calendar", don't hand it to the parser. Split the string and use the component constructor, which works in local time:
function parseLocalDate(text) {
const [y, m, d] = text.split("-").map(Number);
return new Date(y, m - 1, d); // months are zero-based
}
const day = parseLocalDate("2024-03-10");
console.log(day.getFullYear(), day.getMonth() + 1, day.getDate()); // 2024 3 10| Input | Interpreted as | Safe across engines? |
|---|---|---|
| `"2024-03-10"` | UTC midnight | Yes |
| `"2024-03-10T09:00"` | Local time | Yes |
| `"2024-03-10T09:00Z"` | UTC | Yes |
| `"03/10/2024"` | Engine's choice | No |
Exercise
A user in New York (UTC−5 in winter) picks a birthday, and your code runs new Date("2024-01-15").getDate(). What does it print, and how do you get 15?
Show answer
It prints 14. The date-only string is read as UTC midnight, which is 7 PM on January 14 in New York. To get 15, parse the parts with new Date(2024, 0, 15) (as in parseLocalDate), or read the value with getUTCDate().
Exercise
Why is new Date("2024/03/10") a risk even if it works in your browser?
Show answer
It is not in the simplified ISO 8601 format, so the specification leaves its parsing to each engine. Other engines may read it in a different time zone or return an Invalid Date.