[英]In Javascript, how do I turn a date object into a epoch timestamp?
Wed, 07 Dec 2011 15:31:11 GMT
如果我有该日期对象,如何将其转换为unix时间戳(自纪元以来的秒数)?
var unixTimeStamp = (new Date('Wed, 07 Dec 2011 15:31:11 GMT')).getTime() / 1000;
You could use 你可以用
var dateString = "Wed, 07 Dec 2011 15:31:11 GMT";
var mSecondsSinceEpoch = Date(dateString).getTime();
which returns the UNIX Epoch time in milliseconds. 它返回UNIX纪元时间(以毫秒为单位)。 You can leave 'dateString' empty to take the current time.
您可以将'dateString'留空以获取当前时间。 However, when a Date object is cast to a number, it will also return the above.
但是,当Date对象转换为数字时,它也会返回上述内容。 Thus
从而
var mSecondsSinceEpoch = +Date(dateString) // milliseconds
or 要么
var secondsSinceEpoch = (Date(dateString) / 1000) // seconds
also works! 也可以! See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date for more information on the Javascript Date object.
有关Javascript Date对象的更多信息,请参见https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date 。
You can convert into a timestamp by coercing into a number, eg +date
. 您可以通过强制转换为数字来转换为时间戳,例如
+date
。 However, this will return the amount of milliseconds. 但是,这将返回毫秒数。
To get the amount of seconds since epoch, you would need divide by 1000. Since dividing already involves numbers, you can eliminate the +
: 要获得自纪元以来的秒数,您需要除以1000。由于除法已经涉及数字,因此可以消除
+
:
Math.floor(date / 1000); // 1000 ms = 1s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.