Invalid Dates Report NaN With getTime
Failed parses produce an Invalid Date whose getTime is NaN; engines even roll 2026-02-30 to March 2, so strict checks must round-trip through toISOString.
Code
// 解析失败不会得到 null,而是一个 Invalid Date:NaN 时间戳是唯一可靠的判定
function parseDate(value) {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
const inputs = ['2026-03-01T10:30:00Z', 'not-a-date', ''];
for (const input of inputs) {
const parsed = parseDate(input);
console.log(JSON.stringify(input), '->', parsed ? parsed.toISOString() : 'rejected (Invalid Date)');
}
// 直接使用 Invalid Date 会在序列化时抛 RangeError
try {
new Date('not-a-date').toISOString();
} catch (error) {
console.log('toISOString on Invalid Date throws:', error.constructor.name);
}
// 引擎对越界日历日期很宽容:2026-02-30 被滚动到 3 月 2 日而不是拒绝
console.log('2026-02-30 parses as:', new Date('2026-02-30').toISOString().slice(0, 10));
// 严格校验靠回写比对:解析结果格式化回去必须与输入一致
function isRealDate(input) {
const date = new Date(input);
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === input;
}
console.log('strict checks:', ['2026-03-01', '2026-02-30'].map(isRealDate));Output
Captured from a sandboxed run of this snippet in the build pipeline.
"2026-03-01T10:30:00Z" -> 2026-03-01T10:30:00.000Z
"not-a-date" -> rejected (Invalid Date)
"" -> rejected (Invalid Date)
toISOString on Invalid Date throws: RangeError
2026-02-30 parses as: 2026-03-02
strict checks: [ true, false ]Inside the snippet
Two functions do the real work: parseDate guards against NaN timestamps, isRealDate exposes the strict check.
Repetition is limited to for (const input of inputs), which tries each sample string once.
Putting it to use
The main signature reads function parseDate(value)
Running the file prints labeled results such as toISOString on Invalid Date throws:, 2026-02-30 parses as:, strict checks: — one line per failure mode the snippet guards against.
Core lines
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === input;
return Number.isNaN(date.getTime()) ? null : date;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `parseDate`, `isRealDate` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.