【问题标题】:moment.js time changes when formatted格式化时 moment.js 时间会发生变化
【发布时间】:2021-07-01 06:56:17
【问题描述】:
我在使用 moment.js 时遇到了一些奇怪的行为。我有一个带有日期和时区的对象。当我输入moment(obj.start_time).tz(timeZoneName) 时,我得到一个时间Image showing time before formatting。但是,当我使用 format 方法时,时间的值会发生变化,即 moment(obj.start_time).tz(timeZoneName).format('hh:mm a') 会导致不同的时间(在这种情况下,格式化前的时间是晚上 8:51,更改为 12:晚上 51 点自动)。
【问题讨论】:
标签:
javascript
reactjs
momentjs
moment-timezone
【解决方案1】:
您看到的时间戳是一个内部 UTC 值,moment.js 必须保留此值,因为 UTC 偏移量可能会因遵守夏令时的任何单个时区而异。
例如,洛杉矶的 UTC 偏移量从太平洋标准时间(PST,UTC -8 小时)到太平洋夏令时间(PDT,UTC -7 小时)变化。
您在格式化时显示的值是您要转换到的时区中的等效时间。
因此,UTC 时区是晚上 8:51,而您要转换到的时区是下午 12:51:
let ts = "2021-07-05T20:51:00Z";
let timeZoneName = "Etc/GMT+8";
let m = moment(ts).tz(timeZoneName);
console.log("Moment value:", m);
console.log("UTC time:", moment(ts).tz("UTC").format('hh:mm a'));
console.log("Local time:", m.format('hh:mm a'))
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.js"></script>