如何使用 moment js 将字符串转换为时间戳?

How to convert a string into timestamp, with moment js?

我有代表日期的字符串“18/04/19 5:17 PM EDT”。 我正在使用 moment and the add-on moment-timezone,我需要将此字符串转换为时间戳。

我正在尝试:

var date = moment("18/04/19 5:17 PM EDT").format('DD/MM/YY h:m a z');
alert(date);

但这行不通 "invalid date"。

请注意moment(String):

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.

警告: 浏览器支持解析字符串 is inconsistent。因为没有关于应支持哪些格式的规范,所以在某些浏览器中有效的内容在其他浏览器中无效。

为了在解析 ISO 8601 字符串以外的任何内容时获得一致的结果,您应该使用 String + Format

所以你得到 Invalid Date 因为你的输入既不是 ISO 8601 也不是 RFC 2822 可识别的格式,那么你必须在解析它时提供格式参数。

moment(String, String) does not accept 'z' token, so you have to use moment-timezone to parse your input using zone, see Parsing in Zone 文档:

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

可以使用format() and other methods listed in the Displaying section of the docs (e.g. valueOf())来显示moment对象的值。

这是一个活生生的例子:

var date = moment.tz("18/04/19 5:17 PM EDT", 'DD/MM/YY h:m A', 'America/New_York');
console.log(date.valueOf()); // 1555622220000
console.log(date.format());  // 2019-04-18T17:17:00-04:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>

作为旁注,请记住时区缩写不明确,请参阅 here 了解更多信息。