45

I want to convert a string "2013-09-05 15:34:00" into a Unix timestamp in javascript. Can any one tell how to do that? thanks.

Newbie
  • 2,775
  • 6
  • 33
  • 40

5 Answers5

85

You can initialise a Date object and call getTime() to get it in unix form. It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.

(new Date("2013/09/05 15:34:00").getTime()/1000)

It may have decimal bits so wrapping it in Math.round would clean that.

Math.round(new Date("2013/09/05 15:34:00").getTime()/1000)
Mousius
  • 1,105
  • 7
  • 8
12

try

(new Date("2013-09-05 15:34:00")).getTime() / 1000
Mohsen
  • 269
  • 1
  • 3
7

DaMouse404 answer works, but instead of using dashes, you will use slashes:

You can initialise a Date object and call getTime() to get it in unix form. It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.

(new Date("2013/09/05 15:34:00").getTime()/1000)

It may have decimal bits so wrapping it in Math.round would clean that.

Math.round(new Date("2013/09/05 15:34:00").getTime()/1000)
Community
  • 1
  • 1
cumanacr
  • 308
  • 3
  • 8
  • 1
    `(new Date("2013-09-05 15:34:00").replace(/-/g, '/').getTime()/1000)` be careful when using replace function, you should use `g`, otherwise it will only convert the first dash. I waste a lot of time on this. – Zhang Buzz Jun 07 '17 at 15:55
  • I'm not sure why the last comment was upvoted. A `Date` object does not have a `replace` method. Also, this answer is incorrect; using slashes produces the incorrect format for guaranteed parsing by `Date.parse` (what is used by `new Date(string)`). See [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552). – Heretic Monkey Aug 18 '21 at 12:44
5

For this you should check out the moment.s-library

Using that you could write something like:

newUnixTimeStamp = moment('2013-09-05 15:34:00', 'YYYY-MM-DD HH:mm:ss').unix();
ftoyoshima
  • 363
  • 5
  • 10
Mahus
  • 595
  • 1
  • 6
  • 16
3

I would go with date parse myself since it is the native solution. MDN documentation.

const datetimeString = '04 Dec 1995 00:12:00 GMT';
const unixTimestamp = Date.parse(datetimeString);
// unixTimestamp = 818035920000
  • `new Date(string)` uses `Date.parse`. Also, you shouldn't use `Date.parse` on arbitrary formats. See [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552). – Heretic Monkey Aug 18 '21 at 12:46