如何以格式“YYYY-MM-DD hh:mm:ss”转换日期到UNIX时间戳 [英] How to convert date in format "YYYY-MM-DD hh:mm:ss" to UNIX timestamp

查看:1764
本文介绍了如何以格式“YYYY-MM-DD hh:mm:ss”转换日期到UNIX时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我尝试了这段JavaScript代码:

I tried this piece of Javascript code:

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

它有效,但是当我添加时间('2011-07-15 13:18:52')时,它会导致 NaN

And it works, but it results in NaN when I add time('2011-07-15 13:18:52') to the input.

推荐答案

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])
// big gotcha -------------------------^^^
// month must be between 0 and 11, not 1 and 12
console.log(date);
console.log(date.getTime() / 1000);

这篇关于如何以格式“YYYY-MM-DD hh:mm:ss”转换日期到UNIX时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆