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

如何解决Uncaught RangeError: Invalid time value错误?

解决Uncaught RangeError: Invalid time value错误

你的代码有两个核心问题导致报错:

  1. 时间格式处理错误:OpenMeteo API返回的current_weather.time是ISO 8601格式的字符串(比如"2024-05-20T14:30"),直接用字符串乘以1000会得到NaN,而Intl.DateTimeFormat.format()无法处理NaN值。
  2. 空值检查不彻底:myData.current_weather && myData.current_weather.time的写法,当myData.current_weather不存在时,creation_time会是undefined,后续运算同样会得到NaN。

修正后的代码

const DAY_FORMATTER = new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'long', day: 'numeric' });

// 确保拿到有效的时间字符串再处理
if (myData?.current_weather?.time) {
  // 将ISO字符串转为Date对象,再传给格式化方法
  const currentDate = new Date(myData.current_weather.time);
  const formattedDate = DAY_FORMATTER.format(currentDate);
  // 这里可以将formattedDate插入到HTML元素中,比如:
  // document.getElementById('weather-date').textContent = formattedDate;
} else {
  // 处理数据不存在的情况,比如显示默认文本
  // document.getElementById('weather-date').textContent = '无法获取天气时间';
}

关键说明

  • 使用**可选链操作符?.**更安全地访问嵌套属性,避免因某个层级不存在导致的错误。
  • 直接将ISO字符串传入Date构造函数,浏览器会自动解析为正确的时间对象,无需手动转换时间戳。
  • 增加条件判断,只有当时间数据存在时才执行格式化逻辑,避免无效值传入format()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:13:06