Javascript 如何将日期转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38701847/
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
How can I convert a date into an integer?
提问by Pablo.K
I have an array of dates and have been using the map function to iterate through it, but I can't figure out the JavaScript code for converting them into integers.
我有一个日期数组,并且一直在使用 map 函数来遍历它,但是我无法弄清楚将它们转换为整数的 JavaScript 代码。
This is the array of dates:
这是日期数组:
var dates_as_int = [
"2016-07-19T20:23:01.804Z",
"2016-07-20T15:43:54.776Z",
"2016-07-22T14:53:38.634Z",
"2016-07-25T14:39:34.527Z"
];
回答by Alex Bass
var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update: ES6 version:
更新:ES6 版本:
const dates = dates_as_int.map(date => new Date(date).getTime())
回答by Alnitak
Using the builtin Date.parse
function which accepts input in ISO8601 format and directly returns the desired integer return value:
使用Date.parse
接受 ISO8601 格式输入并直接返回所需整数返回值的内置函数:
var dates_as_int = dates.map(Date.parse);
回答by brad
Here what you can try:
您可以在这里尝试:
var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds
回答by Gary Holiday
You can run it through Number()
你可以运行它 Number()
var myInt = Number(new Date(dates_as_int[0]));
If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.
如果参数是 Date 对象,则 Number() 函数返回自 UTC 1970 年 1 月 1 日午夜以来的毫秒数。