如何使用MomentJS将Date转换为时间戳? [英] How to convert Date to timestamp using MomentJS?

查看:3085
本文介绍了如何使用MomentJS将Date转换为时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MomentJS通过以下方式将本地日期转换为UTC日期:

I used MomentJS to convert local date to UTC date using the following way:

$("#div1").text(moment("2016-10-11 18:06:03").tz("Europe/Paris").format());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.6/moment-timezone-with-data.min.js"></script>

<div id="div1"></div>

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

Now I need timestamp from the output value using MomentJS.

推荐答案

您说的是

我使用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.

这篇关于如何使用MomentJS将Date转换为时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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