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

天气App切换城市后时间未同步问题求助(使用Luxon库)

天气App切换城市后时间始终显示本地时间的问题修复

核心问题在于:OpenWeatherMap返回的timezone字段是UTC偏移秒数(例如北京时区对应28800),但你用luxon的setZone()方法时直接传入了这个秒数——而setZone()只识别时区标识符(如Asia/Shanghai)或标准偏移字符串(如+08:00),秒数偏移无法被正确解析,导致时区设置失效,时间始终以本地时区渲染。

修复方案(二选一即可)

方案一:直接基于UTC时间叠加偏移秒数(推荐)

修改weatherService.js中的formatToLocalTime函数,先以UTC初始化时间,再叠加时区偏移:

const formatToLocalTime = (secs, offsetSecs, format = "cccc, dd LLL yyyy' | Local time: 'hh:mm a") => DateTime
    .fromSeconds(secs, { zone: 'utc' }) // 从UTC时间开始
    .plus({ seconds: offsetSecs }) // 加上目标时区的偏移秒数
    .toFormat(format)

方案二:将秒数偏移转换为标准偏移字符串

把秒数偏移转成±HH:mm格式的字符串,再传给setZone():

const formatToLocalTime = (secs, offsetSecs, format = "cccc, dd LLL yyyy' | Local time: 'hh:mm a") => {
    const offsetHours = offsetSecs / 3600;
    // 格式化为±HH:mm的标准偏移字符串
    const offsetStr = `${offsetHours >= 0 ? '+' : ''}${Math.abs(offsetHours).toString().padStart(2, '0')}:00`;
    
    return DateTime
        .fromSeconds(secs)
        .setZone(offsetStr)
        .toFormat(format)
}

额外检查

确认getFormattedWeatherData函数正确传递了从OpenWeatherMap接口获取的timezone值,没有被误修改或遗漏。

内容的提问来源于stack exchange,提问作者Manuel Santamaria Ramos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:22:37