React TypeScript中new Date处理device.timestamp返回Invalid Date的原因
问题原因分析
出现"Invalid Date"主要有两个常见原因:
Unix时间戳单位不匹配
Unix时间戳分为秒级和毫秒级两种格式,而JavaScript的new Date()构造函数默认要求传入毫秒级的时间戳。如果你的device.timestamp是秒级的数值(比如1700000000),直接传入会因为数值过小,解析出超出有效范围的日期,最终显示"Invalid Date"。timestamp类型错误
如果后端返回的timestamp是字符串格式的数字(比如"1700000000"),直接传入new Date()时,会被当作日期字符串而非时间戳解析。由于这种格式不符合日期字符串的规范,也会导致解析失败。
验证与解决方法
- 先打印
device.timestamp的具体值和类型,确认问题:console.log(device.timestamp, typeof device.timestamp); - 根据情况修复:
- 若为秒级数字:
new Date(device.timestamp * 1000).toLocaleString() - 若为字符串格式的秒级时间戳:
new Date(Number(device.timestamp) * 1000).toLocaleString()
- 若为秒级数字:
内容的提问来源于stack exchange,提问作者Ismail Yaman
相关产品推荐
相关产品推荐

