Javascript 如何将格式“YYYY-MM-DD hh:mm:ss”的日期转换为UNIX时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6704325/
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 to convert date in format "YYYY-MM-DD hh:mm:ss" to UNIX timestamp
提问by Amal Kumar S
How can I convert a time in the format "YYYY-MM-DD hh:mm:ss" (e.g. "2011-07-15 13:18:52"
) to a UNIX timestamp?
如何将格式为“YYYY-MM-DD hh:mm:ss”(例如"2011-07-15 13:18:52"
)的时间转换为 UNIX 时间戳?
I tried this piece of Javascript code:
我试过这段 Javascript 代码:
date = new Date("2011-07-15").getTime() / 1000
alert(date)
And it works, but it results in NaN
when I add time('2011-07-15 13:18:52') to the input.
它有效,但是NaN
当我将 time('2011-07-15 13:18:52') 添加到输入时会导致。
回答by Salman A
Use the long date constructor and specify all date/time components:
使用长日期构造函数并指定所有日期/时间组件:
var match = '2011-07-15 13:18:52'.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/)
var date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6])
// ------------------------------------^^^
// month must be between 0 and 11, not 1 and 12
console.log(date);
console.log(date.getTime() / 1000);
回答by Ginden
Following code will work for format YYYY-MM-DD hh:mm:ss
:
以下代码适用于格式YYYY-MM-DD hh:mm:ss
:
function parse(dateAsString) {
return new Date(dateAsString.replace(/-/g, '/'))
}
This code converts YYYY-MM-DD hh:mm:ss
to YYYY/MM/DD hh:mm:ss
that is easily parsed by Date
constructor.
这段代码转换YYYY-MM-DD hh:mm:ss
为构造函数YYYY/MM/DD hh:mm:ss
很容易解析的代码Date
。
回答by RobG
You've accepted an answer, but a much simpler regular expression can be used:
您已接受答案,但可以使用更简单的正则表达式:
function stringToDate(s) {
s = s.split(/[-: ]/);
return new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5]);
}
alert(stringToDate('2011-7-15 20:46:3'));
Of course the input string must be the correct format.
当然输入字符串必须是正确的格式。
回答by Bakudan
回答by Thor Jacobsen
This returns number of milliseconds since Jan. 1st 1970:
Date.parse('2011-07-15 10:05:20')
这将返回自 1970 年 1 月 1 日以来的毫秒数:
Date.parse('2011-07-15 10:05:20')
Just divide by 1000 to get seconds instead of milliseconds..
只需除以 1000 即可获得秒而不是毫秒。