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
221 views
in Technique[技术] by (71.8m points)

javascript - How do I combine moment.js timezone with toDate to build a new date object?

I want to convert a local date object to a date object in another timezone and this is what I have:

moment("2016-08-04T23:30:37Z").tz("Asia/Hong_Kong").format("M/DD/YYYY h:mm a")

>>"8/05/2016 7:30 am"

but if I do

moment("2016-08-04T23:30:37Z").tz("Asia/Hong_Kong").toDate()

>>Thu Aug 04 2016 16:30:37 GMT-0700 (PDT)

As you can see, I can format the moment object to however I like, but how do I return it to a date object again?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

... to a date object in another timezone

The JavaScript Date object cannot represent another time zone. It is simply a timestamp, measured in milliseconds since 1970-01-01 midnight UTC, which you can see with .valueOf() or .getTime().

When you call .toString() on a Date object, or otherwise coerce it into a string (such as when displaying it in the debug console), it converts the timestamp to the local time zone where the environment is running.

Therefore, despite any conversions you do with moment-timezone, you are still talking about the same moment in time, and thus will have the same timestamp in the resulting Date object.

In other words, these are all equivalent:

moment("2016-08-04T23:30:37Z").toDate()
moment.utc("2016-08-04T23:30:37Z").toDate()
moment("2016-08-04T23:30:37Z").tz("Asia/Hong_Kong").toDate()
new Date("2016-08-04T23:30:37Z")

... because they all have the same internal timestamp of 1470353437000

moment("2016-08-04T23:30:37Z").valueOf()                       // 1470353437000
moment.utc("2016-08-04T23:30:37Z").valueOf()                   // 1470353437000
moment("2016-08-04T23:30:37Z").tz("Asia/Hong_Kong").valueOf()  // 1470353437000
new Date("2016-08-04T23:30:37Z").valueOf()                     // 1470353437000

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

...