简体   繁体   English

Moment.Js:使用UTC和时区偏移量抵消日期

[英]Moment.Js: Offsetting dates using UTC and Timezone offset

I am trying to adjust a time using a timezone offset and a UTC timestamp. 我正在尝试使用时区偏移和UTC时间戳来调整时间。

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 我期待的是: 10/16/2013 1:31 PM但我最终10/17/2013 9:31 AM结束

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 . 如果偏移量保持在-480则输出为10/17/2013 5:31 AM

There is a moment#UTC method that initializes the date as UTC vs. local time. 有一个时刻#UTC方法将日期初始化为UTC与本地时间。

I use the jsTimezoneDetect library to determine the timezone name instead of the offset. 我使用jsTimezoneDetect库来确定时区名称而不是偏移量。

Then use this on a UTC timestamp: 然后在UTC时间戳上使用它:

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

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

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