Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" (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.

like image 324
Amal Kumar S Avatar asked Jul 15 '11 08:07

Amal Kumar S


Video Answer


2 Answers

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);
like image 81
Salman A Avatar answered Sep 19 '22 23:09

Salman A


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.

like image 30
Ginden Avatar answered Sep 18 '22 23:09

Ginden