I have to calculate the interval from time duration in javascript. ie, if 100:56:56 to 101:00:00, then duration is 0 hr 3 mins 4 secs .
How to do this in javasript?
I have to calculate the interval from time duration in javascript. ie, if 100:56:56 to 101:00:00, then duration is 0 hr 3 mins 4 secs .
How to do this in javasript?
In Javascript you can do maths on a Date object.
var
date1 = new Date(2010, 07, 07, 05, 00, 00),
date2 = new Date(2010, 07, 21, 15, 30, 00);
return (date2 - date1);
This will return the number of milliseconds between the two dates.
You could then convert that to hours, minutes and seconds if you wanted by dividing by 86400000 for days, then divide the remainder of that by 3600000 for hours, then the remainder of that by 60000 for minutes, etc.
function Time (hour, min, sec) {
this.hour = hour;
this.min = min;
this.sec = sec;
}
Time.parse = function (str) {
var arr = str.split (":");
return new Time (arr [0], arr [1], arr [2]);
};
Time.prototype = {
constructor: Time
, toString: function () {
return [this.hour, this.min, this.sec].join (":");
}
, toSec: function () {
return this.hour * 3600 + this.min * 60 + this.sec;
}
, toMillSec: function () {
return this.toSec () * 1000;
}
, subtract: function (time) {
diff = new Time (
this.hour - time.hour
, this.min - time.min
, this.sec - time.sec
);
if (diff.sec < 0) {
diff.sec += 60;
--diff.min;
}
if (diff.min < 0) {
diff.min += 60;
--diff.hour;
}
return diff;
}
};
var t1 = Time.parse ("101:00:00");
var t2 = Time.parse ("100:56:56");
var t3 = t1.subtract (t2);
t3.toString (); // "0:3:4"
t3.toMillSec (); // 184000