9

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.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Amal Kumar S
  • 15,555
  • 19
  • 56
  • 88

5 Answers5

17

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);
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • dude am getting the timestamp but its not the correct one am getting. when I give '2011-07-15 14:54:12' I get the timestamp as '1313434452'. But when I check this using 'http://www.onlineconversion.com/unix_time.htm' its shows the timestamp converted date to Mon, 15 Aug 2011 07:48:52 GMT which is wrong. – Amal Kumar S Jul 15 '11 at 09:16
15

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.

Ginden
  • 5,149
  • 34
  • 68
6

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
1

Months start from 0, unlike the days! So this will work perfectly (tested)

function dateToUnix(year, month, day, hour, minute, second) {
    return ((new Date(Date.UTC(year, month - 1, day, hour, minute, second))).getTime() / 1000.0);
}
Bakudan
  • 19,134
  • 9
  • 53
  • 73
-3

This returns number of milliseconds since Jan. 1st 1970: Date.parse('2011-07-15 10:05:20')

Just divide by 1000 to get seconds instead of milliseconds..

Thor Jacobsen
  • 8,621
  • 2
  • 27
  • 26