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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:52:13  来源:igfitidea点击:

How to convert date in format "YYYY-MM-DD hh:mm:ss" to UNIX timestamp

javascriptdatedatetimetimestampunix-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 NaNwhen 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:ssto YYYY/MM/DD hh:mm:ssthat is easily parsed by Dateconstructor.

这段代码转换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

Months start from 0, unlike the days! So this will work perfectly (tested)

月从 0 开始,不像天!所以这将完美地工作(已测试

function dateToUnix(year, month, day, hour, minute, second) {
    return ((new Date(Date.UTC(year, month - 1, day, hour, minute, second))).getTime() / 1000.0);
}

回答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 即可获得秒而不是毫秒。