flamey
flamey

Reputation: 2379

JScript: How to calculate difference between two date-times?

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

Upvotes: 1

Views: 2028

Answers (3)

Robusto
Robusto

Reputation: 31883

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.

Upvotes: 4

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827198

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

Upvotes: 4

ntziolis
ntziolis

Reputation: 10221

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

Upvotes: 0

Related Questions