Convert iso date to milliseconds in javascript

Is it possible to convert iso date to milliseconds? for example i want to convert this iso

2012-02-10T13:19:11+0000 

in milliseconds.

Because I want to compare the current date with the created date. Creation date is iso date.

+59
javascript iso isodate
Feb 10 2018-12-12T00:
source share
6 answers

try it

 var date = new Date("11/21/1987 16:00:00"); // some mock date var milliseconds = date.getTime(); // This will return you the number of milliseconds // elapsed from January 1, 1970 // if your date is less than that date, the value will be negative 

EDIT

You have specified an ISO date. It is also accepted by the constructor of the Date object.

 var myDate = new Date("2012-02-10T13:19:11+0000"); var result = myDate.getTime(); 

Edit

The best I have found is to get rid of the offset manually.

 var myDate = new Date("2012-02-10T13:19:11+0000"); var offset = myDate.getTimezoneOffset() * 60 * 1000; var withOffset = myDate.getTime(); var withoutOffset = withOffset - offset; alert(withOffset); alert(withoutOffset); 

Seems to work. Regarding issues with converting an ISO string to a Date object, you can link to the provided links.

EDIT

Fixed bug with incorrect conversion to milliseconds according to Prasad19sara comment.

+95
Feb 10 '12 at 14:33
source share

Reduction of previous decisions -

 var myDate = +new Date("2012-02-10T13:19:11+0000"); 

It performs on-the-fly type conversion and directly displays the date in milliseconds.

Another way is to use the Date util syntax method, which displays the EPOCH time in milliseconds.

 var myDate = Date.parse("2012-02-10T13:19:11+0000"); 
+22
Sep 16 '15 at 0:45
source share

Another option from 2017 is to use Date.parse() . The MDN documentation indicates, however, that it is unreliable until ES5.

 var date = new Date(); // today date and time in ISO format var myDate = Date.parse(date); 

See fiddle for more details.

+4
Apr 26 '17 at 12:06 on
source share

Another possible solution is to compare the current date with January 1, 1970 , you can get January 1, 1970 on new Date(0) ;

 var date = new Date(); var myDate= date - new Date(0); 
+2
Jun 14 '17 at 7:17
source share

Another solution might be to use the Number object parser as follows:

 let result = Number(new Date("2012-02-10T13:19:11+0000")); let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime(); console.log(result); console.log(resultWithGetTime); 

This translates to milliseconds in the same way as getTime() for a Date object

0
Jul 16 '18 at 12:10
source share

Yes you can do it in one line

 let ms = Date.parse('2019-05-15 07:11:10.673Z'); console.log(ms);//1557904270673 
0
May 15 '19 at 9:32
source share



All Articles