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

使用date-fns出现Invalid Time Value错误,代码输出正常却报错求解决

问题:使用date-fns计算帖子发布时长时,输出结果正确但出现“invalid time values”错误

我用date-fns库实现显示帖子发布时长(如“20分钟前”),控制台能正确输出结果,但会抛出“invalid time values”错误。相关代码和控制台输出如下:

我的代码

const TimeAgo = props => {
  let date = props.date
  let results = new Date(date).toDateString()

  let timesAgo = formatDistanceToNow(new Date(results))
  console.log(timesAgo)

控制台输出

2timeAgo.js:17 about 2 months
2timeAgo.js:17 3 months
timeAgo.js:17 4 months

请问问题出在哪里?


问题原因及解决方法

问题出在多余的日期格式转换步骤:你把new Date(date)转成toDateString()后,又再次用new Date()去解析这个字符串。虽然大部分场景下这个字符串能被解析,但在部分时区或特殊日期格式场景下,会出现解析失败,触发"invalid time values"错误。而且这一步转换完全没有必要。

修正后的代码

const TimeAgo = props => {
  const targetDate = new Date(props.date);
  // 提前判断日期是否有效,避免非法日期触发错误
  if (isNaN(targetDate.getTime())) {
    return "无效日期";
  }
  const timesAgo = formatDistanceToNow(targetDate);
  console.log(timesAgo);
  // 组件需要返回渲染内容,这里返回时长文本
  return <span>{timesAgo}</span>;
};

关键说明

  • 直接将props.date转为Date对象,跳过toDateString()的多余转换,消除解析风险
  • 增加无效日期判断,避免传入非法日期字符串时程序报错
  • 组件必须返回JSX元素才能正常渲染,不要遗漏返回逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:33:20