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?
I tried this piece of Javascript code:
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.
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
:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With