2

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?

mangocaptain
  • 1,435
  • 1
  • 19
  • 31
  • 1
    *toDate* returns a Date object. What you are seeing is the result of the implementation dependent [*toString* method](http://ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring) of that Date. Note that Date objects themselves do not have a time zone, that information comes from the host system. The Date's internal time value is UTC. – RobG Aug 05 '16 at 01:26
  • 1
    I'm voting to close this question as off-topic because there is no answer. The OP *is* creating a Date object. – RobG Aug 05 '16 at 01:32

1 Answers1

3

... 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
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575