How can I calculate time difference in JScript between two times in milliseconds or seconds?
For example, between 2010-04-23 15:03 and 2010-05-30 00:41
How can I calculate time difference in JScript between two times in milliseconds or seconds?
For example, between 2010-04-23 15:03 and 2010-05-30 00:41
var d1 = new Date(2010,3,23,15,3);
var d2 = new Date(2010,4,30,0,41);
var delta = Math.abs( d1 - d2 );
The answer will be in milliseconds.
First, you should parse the strings to obtain date objects, I generally use a function like the following, to extract the date parts, and use the Date
constructor:
function parseDate(input) {
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2], // months are 0-based
parts[3], parts[4]);
}
var diff = parseDate("2010-05-30 00:41") - parseDate("2010-04-23 15:03");
// 3145080000 milliseconds