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



我目前在 PST-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 的时间或偏移量以供参考,这可能是可以接受的。

我认为您需要从非 DST 时间戳中获取偏移量,然后修改字符串。

假设有某种日期,这应该会给你一个字符串,它是日期 + DST 无知偏移量:

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("");
}

这应该在 DST 期间减去一个小时,如果这是您想要的。

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

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

最新更新