简体   繁体   中英

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

I am currently in PST at -07:00 from UTC.

If I do this: moment().format('Z') I correctly get -07:00 . Is there a way to (simply) force moment.format() to ignore daylight savings time, (and in my case give me -08:00 )?

The following code will do what you asked:

// 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');

However: You should probably ask yourself why you want to do this. In the vast majority of cases, ignoring DST when it is actually in effect is an error. Your users don't have a choice of whether or not they use DST. If it's applicable in their local time zone, then your code needs to also take it into account. Don't try to defeat it.

On the other hand, if you're simply displaying what the time or offset would be without DST for informational purposes, that is probably acceptable.

This should subtract an hour during DST, if that's what you want.

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

Update: As noted in comments this only works in cases where you know the timezone is 1 hour ahead during DST.

I think you will need to get the offset from a non-DST timestamp and then munge the strings.

Assuming a date of some kind, this should get you a string which is 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("");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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