Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a string to a Unix timestamp in javascript?

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.

like image 509
Newbie Avatar asked Sep 05 '13 10:09

Newbie


People also ask

Can we convert string to timestamp?

To convert a date string to a timestamp: Pass the date string to the Date() constructor. Call the getTime() method on the Date object. The getTime method returns the number of milliseconds since the Unix Epoch.

How do you convert a string to a date in JavaScript?

Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.

How do you convert UTC to Unix?

We can do this by simply multiplying the Unix timestamp by 1000 . Unix time is the number of seconds that have elapsed since the Unix epoch, which is the time 00:00:00 UTC on 1 January 1970 .


1 Answers

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) 
like image 85
Mousius Avatar answered Oct 09 '22 11:10

Mousius