Moment.Js: Offsetting dates using UTC and Timezone offset

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

I am trying to adjust a time using a timezone offset and a UTC timestamp.

I am running the following code:

var date = {     utc: '2013-10-16T21:31:51',     offset: -480 }  var returnDate = moment(date.utc).utc().zone(date.offset).format('MM/DD/YYYY h:mm A');

What I am expecting is: 10/16/2013 1:31 PM but I am ending up with 10/17/2013 9:31 AM

回答1:

Here is what worked for me:

var date = {   utc: '2013-10-16T21:31:51',   offset: 480 }  var returnDate = moment.utc(date.utc).zone(date.offset).format('MM/DD/YYYY h:mm A');

If you noticed, I changed the offset to a positive number. This gave the desired result. If the offset was left at -480 the output was 10/17/2013 5:31 AM.

There is a moment#UTC method that initializes the date as UTC vs. local time.



回答2:

I use the jsTimezoneDetect library to determine the timezone name instead of the offset.

Then use this on a UTC timestamp:

timestamp = moment.tz(timestamp, tz.name()); timestamp.format('MM/DD/YYYY h:mm A');


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!