简体   繁体   中英

MomentJS and timezone/UTC calculations

I have a JavaScript date object which has come from an API; but when I use Moment to do some date manipulation, the timezone component is messed up and the resulting date now uses GMT local time:

var d = new Date("2018-09-30T00:00:00+10:00");
var m1 = moment(d).toDate(); // 2018-09-29T14:00:000Z
var m2 = moment.utc(d).toDate(); // 2018-09-29T14:00:000Z

How do I preserve my timezone information so that when I start adding days/hours etc, the resulting value remains in the +10:00 timezone?

If I look at the moment object created in eg Firefox debugger, I can see that m1 has _tzm:600 and _isUTC:false , whereas m2 has _tzm:600 and _isUTC:true but in both cases, the wrapped _d is 2018-09-29T14:00:000Z and not 2018-09-30T00:00:00+10:00 as I would hope.

If I call:

var m3 = moment(d).format(); // 2018-09-03T00:00:00+10:00

then everything is okay, but now I have a string rather than a Date object

By definition , Date objects are just in UTC:

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January 1970 UTC.

The browser usually will transform this to local time, though.

I am unsure what you are trying to accomplish. However, in general, for printing back the date in a different timezone, string would be the way. As for timezone manipulation, Moment Timezone might be your place to go.

That being said, if your use case is simple, you can try directly parsing the string date moment and using parseZone . It will allow you to capture the exact date and get timezone information as well.

Just a small snippet showing this.

 const date = '2018-09-30T00:00:00+10:00'; const parseZone = moment.parseZone(date); console.log('Original time: ', parseZone.format()); const offsetTimezone = parseZone.format('Z'); console.log('Timezone', offsetTimezone); const utcOffset = parseZone.utcOffset(); console.log('Offset from UTC in minutes', utcOffset); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> 

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