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

sunrise-sunset API返回的UTC时间如何转换为MST本地时间

你可以通过Date对象先把接口返回的UTC时间字符串解析为标准时间,再指定时区转换为MST时间即可,JS内置的时区转换能力可自动处理夏令时切换,无需手动计算时差:

fetch("https://api.sunrise-sunset.org/json?lat=51.2694&lng=-113.9804")
.then(res => res.json())
.then(data => {
    // 拼接日期+时间解析为UTC时间,避免跨天场景的日期偏移问题
    const sunriseUtc = new Date(`${data.results.date} ${data.results.sunrise} UTC`);
    const sunsetUtc = new Date(`${data.results.date} ${data.results.sunset} UTC`);
    // MST对应IANA时区标识符为America/Edmonton,自动适配夏令时
    const formatOptions = {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: true, // 需24小时制可改为false
        timeZone: 'America/Edmonton'
    };
    sunrise.innerHTML = `Sunrise: ${sunriseUtc.toLocaleString('en-US', formatOptions)}`;
    sunset.innerHTML = `Sunset: ${sunsetUtc.toLocaleString('en-US', formatOptions)}`;
})

如果需要固定使用UTC-7的标准MST(不启用夏令时),也可以手动计算时差:

// 手动减去7小时对应的毫秒数
const sunriseMst = new Date(sunriseUtc.getTime() - 7 * 3600 * 1000);
const sunsetMst = new Date(sunsetUtc.getTime() - 7 * 3600 * 1000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:45:04