[英]How to convert date in format "YYYY-MM-DD hh:mm:ss" to UNIX timestamp
How can I convert a time in the format "YYYY-MM-DD hh:mm:ss" (eg "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.它可以工作,但是当我在输入中添加 time('2011-07-15 13:18:52') 时会导致
NaN
。
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);
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
构造函数解析。
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.当然,输入字符串必须是正确的格式。
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 即可获得秒数而不是毫秒数..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.