简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM