使用Moment.js从ISO字符串中提取utcOffset [英] Extracting utcOffset from an ISO String with Moment.js

查看:96
本文介绍了使用Moment.js从ISO字符串中提取utcOffset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用moment.js,我正在尝试从ISO日期字符串中提取偏移量,以便稍后在格式化纪元时间戳时使用偏移量,以确保时间戳的转换位于同一时区。

Using moment.js, I'm attempting to extract the offset from an ISO date string so I can use the offset later when formatting an epoch timestamp to ensure the conversion of the timestamp is in the same timezone.

即使字符串中的偏移量为-0400,结果始终为0;

Even though the offset in the string is -0400, the result is always 0;

var currentTime = "2015-03-18T16:10:00.001-0400";
var utcOffset = moment(currentTime).utcOffset(); // 0

我试图使用parseZone()也没有成功。有没有办法从字符串中提取-0400所以我可以在格式化另一个时间时使用它?

I've attempted to use parseZone() as well without success. Is there a way to extract -0400 from the string so I can use it while formatting another time?

感谢您的帮助!
KC

Thanks for the help! KC

推荐答案

提取偏移的正确方法确实是 parseZone

The correct way to extract the offset is indeed with parseZone

var currentTime = "2015-03-18T16:10:00.001-0400";
var utcOffset = moment.parseZone(currentTime).utcOffset();

这应该导致 -240 ,其中表示UTC后面240分钟,与输入字符串中的 -0400 相同。如果你想要字符串形式,而不是 utcOffset(),你可以使用 .format('Z') for - 04:00 .format('ZZ') for - 0400

This should result in -240, which means 240 minutes behind UTC, which is the same as the -0400 in the input string. If you wanted the string form, instead of utcOffset() you could use .format('Z') for "-04:00" or .format('ZZ') for "-0400".

您在问题中提供的表单只使用计算机的本地时区。所以它在你的时区(或代码运行的任何地方)目前是UTC + 00:00,这可以解释为什么你会得到零。你必须使用 parseZone 来保留输入字符串的偏移量。

The form you gave in the question just uses the computer's local time zone. So it is currently UTC+00:00 in your time zone (or wherever the code is running), that would explain why you would get a zero. You have to use parseZone to retain the offset of the input string.

另外 - 你的用例有点令人担忧的。请记住,偏移时区不同。时区可以在不同的时间点改变其偏移。许多时区都是为了适应夏令时。如果从一个时间戳中选择偏移量并将其应用于另一个时间戳,则无法保证新时间戳的偏移量是正确的。

Also - your use case is a bit worrying. Remember, an offset is not the same thing as a time zone. A time zone can change its offset at different points in time. Many time zones do this to accommodate daylight saving time. If you pick an offset off of one timestamp and apply it to another, you don't have any guarantees that the offset is correct for the new timestamp.

作为示例,考虑美国东部时区,当夏令时于2015年3月8日生效时,该时区刚刚从UTC-05:00变为UTC-04:00。如果您选择的值与您提供的值相同,并将其应用于3月1日的日期,您将把它放入大西洋时区而不是东部时区。

As an example, consider the US Eastern time zone, which just changed from UTC-05:00 to UTC-04:00 when daylight saving time took effect on March 8th, 2015. If you took a value like the one you provided, and applied it to a date of March 1st, you would be placing it into the Atlantic time zone instead of the Eastern time zone.

这篇关于使用Moment.js从ISO字符串中提取utcOffset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆