如何使用 Javascript 将日期转换为自 1970 年以来的毫秒数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7682819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:56:18  来源:igfitidea点击:

How to convert date to milliseconds since 1970 using Javascript?

javascriptdate

提问by TaylorMac

I have these variables: (not literally, but this is what I obtain from a datepicker)

我有这些变量:(不是字面上的,但这是我从日期选择器中获得的)

var StartMonth = "April";
var StartDate = "21";
var CurrentStartTime = "2"; 
var CurrentEndTime = "5";
var Startampm = "PM"; //corresponds to the CurrentStartTime
var Endampm = "PM"; //corresponds to the CurrentEndTime

I need to convert these variables to a single variable, milliseconds since 1970.

我需要将这些变量转换为单个变量,自 1970 年以来的毫秒数。

采纳答案by Greg Hewgill

Use the Dateclass.

使用日期类。

回答by Travis J

jsFiddle demo

jsFiddle 演示

Here is a simple way to do this using the valueOfmethod of Date.

这是使用 的valueOf方法执行此操作的简单方法Date

var d = new Date();
milliseconds since 1970 = d.valueOf();

回答by honzajde

Simply make use of implicit conversions like this:

只需使用这样的隐式转换:

+new Date()

回答by RobG

Convert them to a date using new Date(args), then use Date.prototype.getTime, or just convert the date to a number. It's all in ECMA-262 §15.9.

使用new Date(args)将它们转换为日期,然后使用Date.prototype.getTime,或者只是将日期转换为数字。这一切都在 ECMA-262 §15.9 中。