繁体   English   中英

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

[英]Force Moment.js format() to ignore daylight savings time JS

我现在在UTC时间-07:00

如果我这样做: 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的时间或偏移量,那么这可能是可以接受的。

这应该在夏令时期间减去一小时,如果这是你想要的。

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

更新:如评论中所述,这仅适用于您在DST期间提前1小时知道时区的情况。

我想你需要从非DST时间戳获得偏移量,然后才能获得字符串。

假设某种日期,这应该得到一个日期+ 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("");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM