Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - Initialize a Moment with the timezone offset that I created it with

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.

I would expect that:

moment("2015-12-14T04:00:00Z").utcOffset()

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.

Anyway, I can do

moment("2015-12-14T04:00:00Z").tz("utc").utcOffset()

But my datetime string is dynamic, so I don't know the timezone.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(...) 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...