convert iso date to milliseconds in javascript

萝らか妹 提交于 2019-11-27 03:31:22

Try this

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've provided 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've 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 working. As far as problems with converting ISO string into the Date object you may refer to the links provided.

EDIT

Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.

A shorthand of the previous solutions is

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

It does an on the fly type conversion and directly outputs date in millisecond format.

Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.

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

Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.

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

See the fiddle for more details.

LingYan Meng

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

var date = new Date(); 
var myDate= date - new Date(0);

Another solution could be to use Number object parser like this:

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 converts to milliseconds just like getTime() on Date object

Yes, you can do this in a single line

let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
var date = new Date()
console.log(" Date in MS last three digit = "+  date.getMilliseconds())
console.log(" MS = "+ Date.now())

Using this we can get date in milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!