Sub topic 3
Parsing Strings: Why ISO 8601 Is the Only Safe Format
This chapter assumes you know JavaScript basics and can run code in a browser console or Node.js. It also assumes you have read the earlier chapters: a Date holds one millisecond time value, and new Date(year, monthIndex, day) uses zero-based months. Here you will learn which strings JavaScript parses the same way everywhere, which ones it does not, and how to validate what you get back.
One parser, two entry points
new Date(string) and Date.parse(string) run the same parsing algorithm. The only difference is the return type. The constructor gives you a Date object, and Date.parse gives you the raw time value as a number.
const text = "2024-03-10T08:15:00Z";
const fromConstructor = new Date(text);
const fromParse = Date.parse(text);
console.log(fromConstructor.getTime()); // 1710058500000
console.log(fromParse); // 1710058500000
console.log(typeof fromParse); // "number"The parser works in two stages. It first tries to read the string as the Date Time String Format, a simplified version of ISO 8601 that the ECMAScript specification defines exactly. If the string does not match that format, the engine may use any fallback heuristics it likes. The spec calls this behavior "implementation-specific", so every engine can do something different.
The ISO format the spec guarantees
The full form is YYYY-MM-DDTHH:mm:ss.sssZ. You may drop parts from the right, so all of these are valid:
| String | Meaning | Interpreted as |
|---|---|---|
| `2024` | Year only | UTC, Jan 1 00:00 |
| `2024-03` | Year and month | UTC, Mar 1 00:00 |
| `2024-03-10` | Full date | UTC midnight |
| `2024-03-10T08:15` | Date and time, no offset | Local time |
| `2024-03-10T08:15:30.250` | With seconds and milliseconds | Local time |
| `2024-03-10T08:15Z` | `Z` means UTC | UTC |
| `2024-03-10T08:15+02:00` | Explicit offset | 06:15 UTC |
| `+275760-09-13T00:00:00Z` | Expanded six-digit year with sign | UTC, the largest valid date |
Months and days are always two digits. The separator between date and time is T, and the offset is either Z or +HH:mm / -HH:mm.
The date-only versus date-time rule
This rule causes more bugs than any other part of parsing. A date-only string is treated as UTC, but a date-time string without an offset is treated as local time. The spec chose this for compatibility with older code, and it does not match what ISO 8601 itself says.
const dateOnly = new Date("2024-03-10"); // UTC midnight
const dateTime = new Date("2024-03-10T00:00"); // local midnight
console.log(dateOnly.toISOString()); // "2024-03-10T00:00:00.000Z" everywhere
console.log(dateTime.toISOString()); // depends on your zone, e.g. "2024-03-09T23:00:00.000Z" in Berlin
// In any zone west of UTC, the "date-only" value shows as the previous day locally:
console.log(dateOnly.getDate()); // 9 in New York, 10 in BerlinIf a user in New York picks "March 10" from a form and you run new Date("2024-03-10").getDate(), you get 9. The stored instant is correct. The bug comes from reading a UTC midnight through local getters.
Strings outside the format
The spec only requires an engine to parse back what its own toString() and toUTCString() produce. Everything else is up to the engine. The results below are typical of V8 (Chrome, Node.js), and other engines may differ.
const samples = [
"2024/03/10", // slashes: usually local midnight in V8
"2024-3-10", // single-digit month: not ISO; local in V8, Invalid in some engines
"03/10/2024", // US order assumed: March 10, never October 3
"10 March 2024", // English month names: works in many engines, not guaranteed
"2024-03-10 08:15", // space instead of T: accepted by V8, rejected by older Safari
"10.03.2024", // German style: often Invalid Date
];
for (const s of samples) {
const d = new Date(s);
console.log(s.padEnd(20), Number.isNaN(d.getTime()) ? "Invalid Date" : d.toString());
}Avoid locale-style strings such as 03/10/2024 in particular. An engine that parses them assumes month/day order, so a European user's "10 March" becomes October 3, with no error raised. The Intl API formats dates for display but has no matching parser, so it cannot help here.
Invalid Date and how to detect it
When parsing fails, you still get a Date object back. Its time value is NaN, and each method reacts in its own way:
const bad = new Date("not a date");
console.log(bad instanceof Date); // true: it is still a Date
console.log(bad.getTime()); // NaN
console.log(String(bad)); // "Invalid Date"
console.log(JSON.stringify({ bad })); // '{"bad":null}'
try {
bad.toISOString();
} catch (err) {
console.log(err.name); // "RangeError"
}
function isValidDate(value) {
return value instanceof Date && !Number.isNaN(value.getTime());
}
console.log(isValidDate(bad)); // false
console.log(isValidDate(new Date("2024-03-10"))); // truePay attention to the JSON case. An invalid date serializes to null without an error, so a bad value can reach your API without anyone noticing. Validate dates before you serialize them.
Out-of-range components
According to the spec, "2024-02-30" is not a valid instance of the format and should produce an Invalid Date. Engines disagree: V8 accepts a day up to 31 in any month and rolls "2024-02-30" over to March 1, while Firefox returns Invalid Date. A string that matches the pattern can still hold an impossible date, so you cannot treat a successful parse as proof the input was valid.
A strict parser for date input
For input you do not control, such as form fields, CSV files, or third-party APIs, check the shape with a regular expression. Then build the Date from its components and confirm that nothing rolled over.
function parseLocalDate(text) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
if (!match) return null;
const [, year, month, day] = match.map(Number);
const date = new Date(year, month - 1, day); // local midnight, zero-based month
// Reject rollover such as Feb 30 -> Mar 1, and years 0000-0099,
// which the component constructor maps to 1900-1999.
if (
date.getFullYear() !== year ||
date.getMonth() !== month - 1 ||
date.getDate() !== day
) {
return null;
}
return date;
}
console.log(parseLocalDate("2024-02-29")?.toDateString()); // "Thu Feb 29 2024"
console.log(parseLocalDate("2023-02-29")); // null (not a leap year)
console.log(parseLocalDate("2024-13-01")); // null
console.log(parseLocalDate("03/10/2024")); // null (wrong shape)This function gives local midnight on purpose, so local getters return the same day the user typed. If you need a UTC calendar date instead, use new Date(Date.UTC(year, month - 1, day)) and compare against the getUTC* getters.
Summary of safe practice
- Parse only the ISO Date Time String Format. Treat anything else as untrusted and unportable.
- Remember that date-only strings are read as UTC and offset-less date-times as local time.
- Always check for
NaNafter parsing, because no exception is thrown. - Validate components yourself when the string comes from a person.
- Include
Zor an offset whenever a string represents a specific instant.
Exercise
A user in Los Angeles (UTC-8 in winter) selects "2024-01-15" in a form. Your code runs new Date("2024-01-15").getDate(). What does it return, and what are two ways to fix it?
Show answer
It returns 14. The date-only string is parsed as 2024-01-15T00:00Z, which is 16:00 on January 14 in Los Angeles, and getDate reads local time. Fix it by reading with getUTCDate() (and the other getUTC* methods), or by parsing the components and building local midnight with new Date(2024, 0, 15), as parseLocalDate does.
Exercise
Why is new Date("05/06/2024") unsafe even though it gives a valid date in Chrome?
Show answer
The string is not in the ISO format, so its meaning is implementation-specific. Engines that accept it assume US month/day order (May 6), while a user writing day/month meant June 5. The ambiguity produces no error, and other engines may return Invalid Date.
Exercise
What does JSON.stringify({ when: new Date("2024-02-31x") }) produce, and why is this risky?
Show answer
It produces '{"when":null}'. The string fails to parse, so the result is an Invalid Date, and Date.prototype.toJSON returns null for an invalid date instead of throwing. The bad value is sent without any error, so validate with Number.isNaN(date.getTime()) before serializing.