47

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.

5 Answers 5

86

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)
Sign up to request clarification or add additional context in comments.

2 Comments

That is gonna also convert the given datetime to your local time in timestamp.
It's also not guaranteed to work with that string format.
12

try

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

Comments

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)

2 Comments

(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.
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?.
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();

1 Comment

I think the right format for minutes is mm. So the second argument of moment is 'YYYY-MM-DD HH:mm:ss
5

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

2 Comments

new Date(string) uses Date.parse. Also, you shouldn't use Date.parse on arbitrary formats. See Why does Date.parse give incorrect results?.
thanks. what does it return if it can't parse it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.