简体   繁体   English

在Javascript中,如何将日期对象转换为纪元时间戳?

[英]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.

相关问题 如何使用 JavaScript 将纪元时间戳转换为正常的日期时间格式? - How to convert epoch timestamp to normal date time format using JavaScript? 使用 Javascript 将日期转换为纪元时间戳 - Covert date to epoch timestamp using Javascript 你如何在javascript中将纪元转换为可读日期格式 - how do you convert epoch to readable date format in javascript 如何将UNIX时间戳转换为Google Sheets日期值? - How can I turn a UNIX timestamp into a Google Sheets date value? 如何使用时刻 javascript 将日期 22/04/2020 转换为纪元时间戳 - how to convert the date 22/04/2020 to Epoch timestamp using moment javascript javascript从epoch字符串转换为Date对象 - javascript convert from epoch string to Date object 增加日期 Object 而不转换为 Javascript 中的纪元 - Increment Date Object in without converting to epoch in Javascript 如何将日期组件数组转换为JavaScript日期对象? - How to turn an array of date components into a JavaScript date object? 如何将Oracle Date对象/ Long转换为javascript日期? - How do I convert an Oracle Date object/Long into a javascript date? 在Django中,如何将Python日期时间字符串转换为Javascript Date对象? - Within Django, how can I turn my Python datetime string into a Javascript Date object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM