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

Node.js使用moment进行时区转换生成UTC过期时间结果不符合预期

错误原因

代码中使用的hh是12小时制的时间格式标识符,仅支持0-12的小时数值,你构造的23:59:59用hh解析时会被自动转换为12小时制的11 PM,上海时区为UTC+8,11点减去8小时得到UTC时间的3点,和你实际得到的03:59:59结果完全吻合。

解决方案

将所有时间格式化语句中的hh替换为代表24小时制的格式标识符HH即可。另外你代码中用currentDate.getDate()等方法获取年月日的逻辑是冗余的,该方法获取的是代码运行环境的本地日期,不是目标用户时区的日期,你已经通过localizedDate拿到了正确的用户时区日期,冗余代码可以直接删除,避免跨零点场景下出现日期错误。

修正后代码
let timezone = tzlookup(latitude, longitude);
let currentDate = new Date()
let localizedDateAndTime = moment.tz(currentDate, timezone).format('YYYY-MM-DD HH:mm:ss')
let localizedDate = moment.tz(currentDate, timezone).format('YYYY-MM-DD')
console.log("Timezone: " + timezone)
console.log("Local Time: " + localizedDateAndTime)
console.log("UTC Time: " + moment.tz(currentDate, 'UTC').format())
let currentTimestamp = localizedDate + " " + 23 + ":" + 59 + ":" + 59
console.log("Localized timestamp: " + currentTimestamp)
var localizedMoment = moment.tz(currentTimestamp, 'YYYY-MM-DD HH:mm:ss', timezone);
var utcMoment = localizedMoment.utc()
console.log("UTC Moment (when event expires in UTC): " + utcMoment.format('YYYY-MM-DD HH:mm:ss'))
let timestamp = utcMoment.format('YYYY-MM-DD HH:mm:ss')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:48:03