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 20开发者_如何学C10-04-23 15:03 and 2010-05-30 00:41
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
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.
Check out the JS DateTime library on CodePlex. It lets you handle DateTimes the same way .NET does (well with some restrictions of course).
精彩评论