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

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.


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.