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

如何将API返回的Unix时间戳转换为本地时间(React场景)

解决Unix时间戳转本地时间字符串的问题

你可以通过Date对象将UptimeRobot返回的秒级Unix时间戳转换为本地时间字符串,同时修正useEffect依赖项避免无限循环,修改后的代码如下:

useEffect(() => {
  const postdata = {
    api_key: apiKey,
    format: "json",
    logs: 1,
    custom_uptime_ranges: "1658892600_1658979000-1658946600_1659033000",
  };
  const url = "https://api.uptimerobot.com/v2/getMonitors";
  const getData = async () => {
    try {
      const response = await fetch(url, {
        method: "POST",
        body: JSON.stringify(postdata),
        headers: { "Content-type": "application/json" },
      });
      const responseData = await response.json();
      const customData = responseData.monitors.map((i) => ({
        title: i.friendly_name,
        uptime: i.custom_uptime_ranges,
        // 将秒级时间戳转为本地时间字符串
        date: new Date(i.logs[0].datetime * 1000).toLocaleString()
      }));
      console.log(responseData);
      setApiData(customData);
      // 注意:setApiData是异步操作,直接打印apidata会拿到旧值,需通过useEffect监听apidata查看更新后的值
    } catch (error) {
      console.error("获取数据失败:", error);
    }
  };
  getData();
}, []); // 改为空数组,仅在组件挂载时执行一次,避免无限循环

关键说明:

  • 时间戳转换:UptimeRobot返回的datetime是秒级Unix时间戳,而JavaScript的Date构造函数需要毫秒级时间戳,因此要乘以1000。
  • 自定义时间格式:如果需要指定时间显示格式(比如固定为YYYY-MM-DD HH:mm:ss),可以使用Intl.DateTimeFormat自定义配置:
    date: new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).format(new Date(i.logs[0].datetime * 1000))
    
  • 依赖项修正:原代码依赖apidata会导致每次状态更新后重复触发请求,造成无限循环,改为空数组即可确保请求仅执行一次。
  • 错误处理:添加try/catch捕获请求过程中的异常,避免程序因请求失败崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:39:13