且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用MomentJS将Date转换为时间戳?

更新时间:2022-01-18 04:01:40

您说的是

我使用MomentJS通过以下方式将本地日期转换为UTC日期: moment("2016-10-11 18:06:03").tz("Europe/Paris").format()

I used MomentJS to convert local date to UTC date using the following way: moment("2016-10-11 18:06:03").tz("Europe/Paris").format()

那不行.它将本地值转换为巴黎时间,并以ISO8601格式的字符串形式发出.

That doesn't do that. That converts a local value to Paris time, and emits it as a string in ISO8601 format.

现在我需要使用MomentJS从输出值中添加时间戳.

Now I need timestamp from the output value using MomentJS.

这是一个不同的问题,并且不会涉及上述内容,因为:

That's a different question, and wouldn't involve the output of the above because:

  1. 您无法从输出字符串获取时间戳,而会从moment对象获取时间戳.您可以解析该字符串,但这会很愚蠢,因为您之前已经有一个moment对象.

  1. You can't get a timestamp from the output string, you'd get it from a moment object. You could parse that string, but that would be silly since you already had a moment object earlier.

时间戳是基于UTC的,因此时区转换是无关紧要的.如果您根本不进行转换,则将获得相同的时间戳.

Timestamps are UTC based, so time zone conversion is irrelevant. You'd get the same timestamp if you didn't convert at all.

您可以使用.format('X').format('x')获得带有时间戳的字符串,具体取决于所需的精度.但是,再次使用.valueOf().unix()来获得数字时间戳记要干净得多,再次取决于精度.

You can get a string with a timestamp using .format('X') or .format('x') depending on which precision you want. But it's much cleaner to just get the numerical timestamp using .valueOf() or .unix(), again depending on precision.