如何将moment.js时区与toDate结合使用以构建新的日期对象? [英] How do I combine moment.js timezone with toDate to build a new date object?

查看:136
本文介绍了如何将moment.js时区与toDate结合使用以构建新的日期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将本地日期对象转换为另一个时区的日期对象,这就是我所拥有的:

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"

但如果我这样做

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?

推荐答案


...到另一个时区的日期对象

... to a date object in another timezone

JavaScript 日期对象不能代表另一个时区。它只是一个时间戳,以1970-01-01午夜UTC后的毫秒数为单位,您可以使用 .valueOf() .getTime( )

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

当你在<$ c $上拨打 .toString()时c> Date 对象,或以其他方式将其强制转换为字符串(例如在调试控制台中显示时),它将时间戳转换为运行环境的本地时区。

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")

...因为它们都具有相同的内部时间戳of 1470353437000

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

这篇关于如何将moment.js时区与toDate结合使用以构建新的日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆