Date to timestamp in javascript

Is it possible in javascript to convert some date to a timestamp?

I have a date in this format 2010-03-09 12:21:00 and I want to convert it to its equivalent timestamp using javascript.

+4
source share
3 answers

In response to your edit:

You need to parse a date string to build a Date object, and then you can get a timestamp, for example:

 function getTimestamp(str) { var d = str.match(/\d+/g); // extract date parts return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object } getTimestamp("2010-03-09 12:21:00"); // 1268158860000 

In the above function, I use a simple regular expression to extract numbers, then I build a new Date object using a date constructor with this (Note: The Date object treats months as 0 based numbers, for example Jan-0, Feb-1, .. ., 11-Dec).

Then I use the unary plus operator to get the timestamp.

Note that the timestamp is expressed in milliseconds.

+18
source
 +(new Date()) 

Is the work in progress.

+9
source

The getTime() method of instances of a Date object returns the number of milliseconds since an era; which is a pretty good timestamp.

+3
source

Source: https://habr.com/ru/post/1303530/


All Articles