使用创建时区的偏移量初始化Moment [英] Initialize a Moment with the timezone offset that I created it with
问题描述
我在javascript中使用了矩和矩时区,而这部分是我见过的最不直观的API之一.
I'm using moment and moment-timezone in javascript, and this part of it is one of the most unintuitive API's I've ever seen.
我希望:
moment("2015-12-14T04:00:00Z").utcOffset()
将是一个纯函数,并返回参数中包含的偏移量,该偏移量为0.但是相反,它隐式将其转换为我的本地时区偏移量(PST),因此返回-480,为什么?我问我刚刚创建的对象有什么偏移量,而不是我当前所在的偏移量.这就像我编写了一个api,在其中调用User.find(123).name()返回您的姓名而不是用户名123.
would be a pure function and return the offset included in the argument, which is 0. But instead it implicitly converts it to my local timezone offset (PST), so this returns -480 Why?? I asked what offset the object i just created has, not what offset I'm currently in. It would be like if I wrote an api where calling User.find(123).name() returns your name instead of the name of user 123.
无论如何,我可以做
moment("2015-12-14T04:00:00Z").tz("utc").utcOffset()
但是我的日期时间字符串是动态的,所以我不知道时区.
But my datetime string is dynamic, so I don't know the timezone.
如何获得我所期望的行为,即js中的一瞬间,该瞬间位于我传入的字符串中所包含的时区偏移中?
How can I get the behavior I expected, a Moment in js that is in the timezone offset included in the string i passed in?
推荐答案
使用parseZone
保留传入的偏移量.
Use parseZone
to keep the offset as it was passed in.
moment.parseZone("2015-12-14T04:00:00Z")
关于为什么?"问题的一部分:
As to the "why?" part of your question:
-
moment(...)
是本地模式.歧义输入(无偏移)被假定为本地时间.明确的输入(具有偏移量)已根据当地时间进行了调整. -
moment.utc(...)
是utc模式.歧义输入假定为UTC.明确的输入已调整至UTC. -
moment.parseZone()
保持输入区域通过.如果输入不明确,则与本地模式相同.
带有moment-timezone插件的 -
moment.tz(...)
可以解析特定时区的输入.
moment(...)
is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time.moment.utc(...)
is utc mode. Ambiguous input is assumed to be UTC. Unambiguous input is adjusted to UTC.moment.parseZone()
keep the input zone passed in. If the input is ambiguous, it is the same as local mode.moment.tz(...)
with the moment-timezone plugin can parse input in a specific time zone.
请记住,这一时刻必须应对各种各样的输入.
Keep in mind that moment has to contend with a wide variety of inputs.
还请记住,时区和时区偏移是两件事.偏移量-08:00
不一定表示您在美国太平洋时区.
Also keep in mind that a time zone and a time zone offset are two different things. An offset of -08:00
doesn't necessarily mean you are in the US Pacific time zone.
这篇关于使用创建时区的偏移量初始化Moment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!