gpt4 book ai didi

javascript - 强制 Moment.js format() 忽略夏令时 JS

转载 作者:行者123 更新时间:2023-11-29 16:02:13 24 4
gpt4 key购买 nike

我目前在太平洋标准时间 -07:00 来自 UTC。

如果我这样做:moment().format('Z') 我会正确地得到 -07:00。有没有办法(简单地)强制 moment.format() 忽略夏令时,(在我的例子中给我 -08:00)?

最佳答案

以下代码将执行您的要求:

// First we need to get the standard offset for the current time zone.
// Since summer and winter are at opposite times in northern and summer hemispheres,
// we will take a Jan 1st and Jul 1st offset. The standard offset is the smaller value
// (If DST is applicable, these will differ and the daylight offset is the larger value.)
var janOffset = moment({M:0, d:1}).utcOffset();
var julOffset = moment({M:6, d:1}).utcOffset();
var stdOffset = Math.min(janOffset, julOffset);

// Then we can make a Moment object with the current time at that fixed offset
var nowWithoutDST = moment().utcOffset(stdOffset);

// Finally, we can format the object however we like. 'Z' provides the offset as a string.
var offsetAsString = nowWithoutDST.format('Z');

但是:您可能应该问问自己为什么您想要这样做。在绝大多数情况下,在 DST 实际生效时忽略它是错误的。您的用户无法选择是否使用 DST。如果它适用于本地时区,那么您的代码也需要考虑到这一点。不要试图打败它。

另一方面,如果您只是为了提供信息而显示没有 DST 的时间或偏移量,那可能是可以接受的。

关于javascript - 强制 Moment.js format() 忽略夏令时 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51200976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com