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

页面显示Invalid Date如何修复?数据库无对应数据时如何让日期展示为空

问题原因

当 user.items?.firstDateseconds 不存在、为undefined/null或其他非合法数值时,new Date() 接收的参数会被转为 NaN,生成无效日期对象,调用toDateString() 就会返回 Invalid Date 字符串。

解决办法

添加合法性判断,仅当时间戳为有效数值时才渲染日期文本,否则渲染空内容。

写法1(简洁版,适配绝大多数业务场景)

如果你的业务逻辑里不会出现等于0的合法时间戳,可以直接用短路判断简化书写:

First Item:
{user.items?.firstDateseconds && new Date(user.items.firstDateseconds * 1000).toDateString()}

写法2(严谨版,兼容0值时间戳)

如果要兼容1970年附近的时间戳(即时间戳可能为0),可以用Number.isFinite做精准判断:

First Item:
{Number.isFinite(user.items?.firstDateseconds) ? new Date(user.items.firstDateseconds * 1000).toDateString() : ''}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:51:00