编程语言
首页 > 编程语言> > javascript – 如何将格式为“YYYY-MM-DD hh:mm:ss”的日期转换为UNIX时间戳

javascript – 如何将格式为“YYYY-MM-DD hh:mm:ss”的日期转换为UNIX时间戳

作者:互联网

如何将格式为“YYYY-MM-DD hh:mm:ss”(例如“2011-07-15 13:18:52”)的时间转换为UNIX时间戳?

我试过这段Javascript代码:

date = new Date("2011-07-15").getTime() / 1000
alert(date)

并且它可以工作,但是当我在输入中添加时间(‘2011-07-15 13:18:52’)时会导致NaN.

解决方法:

使用长日期构造函数并指定所有日期/时间组件:

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);

标签:javascript,timestamp,datetime,date,unix-timestamp
来源: https://codeday.me/bug/20191007/1869108.html