views:

333

answers:

3

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

A: 

Check out the JS DateTime library on CodePlex. It lets you handle DateTimes the same way .NET does (well with some restrictions of course).

ntziolis
+3  A: 
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.

Robusto
That should be `new Date(2010,3,23,15,3)`. The month needs to be `- 1` (Jan = 0, Feb = 1, etc.) and you should avoid a leading zero unless you are using octal based numbers. Dito for the second `Date`.
RoToRa
@RoToRa: Yeah, thanks. I just regexed the hyphens, spaces and colons out of his dates without looking at the values themselves. Edited to reflect this.
Robusto
No need for the `valueOf` s.
Tim Down
Robusto
+3  A: 

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
CMS