Moment.js timezone valueOf returning wrong timestamp

Deadly 提交于 2019-12-30 07:32:10

问题


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



来源:https://stackoverflow.com/questions/36845923/moment-js-timezone-valueof-returning-wrong-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!