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.
Asked
Active
Viewed 1e+01k times
45

Newbie
- 2,775
- 6
- 33
- 40
5 Answers
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
-
5That is gonna also convert the given datetime to your local time in timestamp. – Adry Feb 21 '18 at 11:10
-
It's also not guaranteed to work with that string format. – Heretic Monkey Aug 18 '21 at 12:28
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)
-
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
-
1I think the right format for minutes is `mm`. So the second argument of `moment` is `'YYYY-MM-DD HH:mm:ss` – Corentin MERCIER Nov 30 '19 at 17:50
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

Jordan Bice
- 31
- 2
-
`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