Moment.js timezone valueOf returning wrong timesta

2019-01-19 08:53发布

问题:

I want to use moment.js to shift an input moment to a different timezone and get its timestamp.

moment.tz(moment(), "Pacific/Auckland").valueOf();

The problem is, while I am doing this, the moment.tz() object is looking good, but the valueOf() method is somehow calculating this back to timezone which is set on my computer.

What is wrong with my approach?

Thanks very much.

EDIT 1

moment.tz(moment(), "Pacific/Auckland").format(); is giving me the right time string

moment.tz(moment(), "Pacific/Auckland").valueOf("x"); is giving me the milliseconds, but again in my local time and not in "Pacific/Auckland" time

So somehow the calculation of milliseconds is converting it back to the local time, but why? And whats the correct approach to get the milliseconds in the expected timezone?

回答1:

I think there might just be a conceptual lack of understanding of what the timestamp actually is.

Let's say the current time where I am is:

04/25/2016 @ 10:21am (UTC-7)

What is the timestamp of this moment?

1461604867

What is the UTC time?

04/25/2016 @ 5:21pm (UTC)

What is the timestamp of this moment?

1461604867

What, the same, why?

A moment in time is the same timestamp, regardless of which timezone it is in. When you call moment(), it is referring to right NOW, this particular moment in time in the grand space-time continuum. Same with Date.now(). The moment you are reading this is, in reality, still the exact same moment where you are, where I am, in Japan, in Antarctica, in Syria, in Greenland, etc. It just so happens that this one moment is visually represented (the time string) by humans in different ways in each area.

Moment timezone does not affect the actual Date object it stores. It only affects the visual representation of the date. The visual representation varies across timezone. That is why you will not get a different timestamp.



回答2:

var time  = moment.tz("2016-04-25 12:00", "Pacific/Auckland");

then

time.format();

Try this