简体   繁体   English

moment.js不会将具有特定时区的时间戳转换为Unix时间戳

[英]moment.js does not convert timestamps with specific timezones to unix timestamps

I am using moment.js to convert a bunch of timestamps in it's specific timezone to a unix timestamp like this: 我正在使用moment.js将特定时区中的一堆时间戳转换为这样的unix时间戳:

var timestamp = "2015-12-29T09:35:00.000-08:00";
console.log(moment("2015-12-29T09:35:00.000-08:00").unix();
console.log(moment("2015-12-29T09:35:00.000-08:00").tz("America/Los_Angeles").unix();

The console log of both the above statements is for some reason, the same - 1451361900. This unix timestamp which it is logging is in my local timezone and not the one I asked for: "America/Los_Angeles". 上面两个语句的控制台日志出于某种原因都是相同的-1451361900。它正在记录的UNIX时间戳记位于我的本地时区,而不是我要求的时区:“ America / Los_Angeles”。 What am I missing? 我想念什么?

A unix timestamp, or Posix, should always be in the UTC (Coordinated Universal Time) format. Unix时间戳或Posix应该始终采用UTC(世界标准时间)格式。

Moment is just doing something like 时刻只是在做类似的事情

function unix () {
    return Math.floor(+this / 1000);
}

Where it converts the date object to an integer and then converts from milliseconds to seconds. 在此将日期对象转换为整数,然后从毫秒转换为秒。

The starting point is a regular javascript Date object, and the ECMA standard says 起点是常规的javascript Date对象,而ECMA标准规定

Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC. 日期对象基于时间值,该时间值是自UTC 1970年1月1日以来的毫秒数。

so date objects are always UTC when converted to the number of milliseconds since 1. January 1970 (epoch), ie you can't set another timezone on a Unix timestamp, both your dates are the same. 因此,将日期对象转换为自1970年1月1日(纪元)以来的毫秒数时,始终是UTC。也就是说,您不能在Unix时间戳上设置另一个时区,两个日期都相同。

The proper way is to use moment-Timezone is this. 正确的方法是使用moment-Timezone

console.log(moment("2015-12-29T09:35:00").unix());
console.log(moment.tz("2015-12-29T09:35" , "America/Los_Angeles").unix());

In above your are providing time zone as a string too which is this last part ".000-08:00" and then you are providing another zone, which is incorrect. 在上面,您还以字符串形式提供时区,这也是最后一部分“ .000-08:00”,然后您提供了另一个时区,这是不正确的。

As you are trying to find out the unix timestamp for the date " 2015-12-29T09:35:00.000-08:00 ". 当您尝试查找日期为“ 2015-12-29T09:35:00.000-08:00 ”的Unix时间戳时。 In this date format timezone value is already present which is " -08:00 ", hence you get the same unix timestamp. 在此日期格式中,时区值已经存在,为“ -08:00 ”,因此您将获得相同的Unix时间戳。

For getting the unix timestamp desired solution, remove the timezone value and use moment-timezone as : 为了获得unix时间戳所需的解决方案,请删除时区值,并将moment-timezone用作:

console.log(moment.tz("2013-12-01", "America/Los_Angeles").unix()); console.log(moment.tz(“ 2013-12-01”,“ America / Los_Angeles”)。unix());

For more details check moment-timezone 有关更多详细信息,请检查moment-timezone

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM