You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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()时,会被当作日期字符串而非时间戳解析。由于这种格式不符合日期字符串的规范,也会导致解析失败。

验证与解决方法

  1. 先打印device.timestamp的具体值和类型,确认问题:
    console.log(device.timestamp, typeof device.timestamp);
    
  2. 根据情况修复:
    • 若为秒级数字:
      new Date(device.timestamp * 1000).toLocaleString()
      
    • 若为字符串格式的秒级时间戳:
      new Date(Number(device.timestamp) * 1000).toLocaleString()
      

内容的提问来源于stack exchange,提问作者Ismail Yaman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:50:19