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

时间:2018-07-05 23:05:21

标签: javascript momentjs dst

我目前位于世界标准时间-07:00的PST。

如果我这样做:moment().format('Z')我正确地得到了-07:00。 有没有办法(简单地)强迫moment.format()忽略夏令时(在我的情况下,请给我-08:00)?

3 个答案:

答案 0 :(得分:0)

以下代码将按照您的要求进行操作:

// 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的时间或偏移量,那可能是可以接受的。

答案 1 :(得分:-1)

如果需要的话,应该在DST期间减去一个小时。

moment().subtract(moment().isDST() ? 1 : 0, ‘hours’).format('Z')

更新:如评论中所述,这仅在您知道夏令时在夏令时提前1小时的情况下有效。

答案 2 :(得分:-1)

我认为您将需要从非DST时间戳记获取偏移量,然后调整字符串。

假设某个日期,这应该为您提供一个字符串,该字符串为date + DST-ignorant-offset:

function _noDST(noDST, dateStr){
    var beginningOfTimeNoDST = moment(noDST); // whatever target you know has no DST
    var d = moment(dateStr);
    var noOffset = d.format('YYYY-MM-DDTHH:mm:ss');
    var offset = beginningOfTimeNoDST.format('Z');
    return [noOffset, offset].join("");
}