RangeError: 无效 Date
错误信息
无效 Date
快速摘要
你通过无效值 到 Date constructor, resulting in 无效 Date 对象那个返回 NaN for 所有方法.
为什么发生
通过 malformed date 字符串到 新 Date()
Used 无效 date 如 February 31st
通过非-date 值那个 cannot 是 parsed
最小示例
✗ 错误代码
const date = new Date("not-a-date");
console.log(date.getTime()); // NaN✓ 修复代码
const date = new Date("2024-01-15");
if (isNaN(date.getTime())) {
console.log("Invalid date");
} else {
console.log(date.getTime());
}无效 date 字符串 produce 无效 Date 对象. 总是检查使用 isNaN(date.getTime()).
如何诊断
检查值 是通过到 新 Date()
Call isNaN(date.getTime()) 到检查如果 date 是无效
Log date 对象 — 它 shows '无效 Date' 如果输入是 坏
如何修复
验证 date 字符串格式之前创建 Date
Use isNaN(date.getTime()) 到 detect 无效 dates and provide fallback
Parse date 组件 separately (year, month, day) for reliability
如何预防
验证 date 输入之前 constructing Date 对象
Use date 库 (date-fns, luxon) for reliable parsing