I am on a time calculation to calculate a delay time for a train Schedule time : t1 Arrival time : t2
function tomdiff(t1,t2) {
var t1 = hour2mins(t1); var t2=hour2mins(t2);
var ret = mins2hour(parseInt(t2-t1));
if(t2<t1) {ret=mins2hour(parseInt(parseInt(t2+1440)-t1));}
return ret;
}
//Calculate on Key up
$("input.[rel=time1]").keyup(function (b){ $("#delaytime").val(tomdiff($("#schedule").val(),$("#arrival").val())); });
This is working great but what if the train arrive earlier!
Can someone advise me?
The fundamental problem is that you're trying to handle wrapping across midnight (the magic number 1440
minutes is 24 hours) with insufficient information.
If t1
and t2
are Date
instances, the code doesn't have to do all that mucking about with hours and minutes, and doesn't have to worry about midnight:
function tomdiff(t1, t2) {
var msdiff;
msdiff = t2 - t1; // When you perform arithmetic on dates, their
// underlying EpochMS value (milliseconds since
// Jan 1, 1970) is used
return msdiff / 1000 / 60; // Milliseconds => minutes
}
If t1
and t2
are not Date
instances, they should be. :-) Presumably you have the date as well as time of the train's scheduled and actual arrival times. The Date
constructor lets you feed those in:
new Date(year, month, day [, hour, minute, second, millisecond ])
If you find yourself needing to do a lot with date/time calculations (and parsing and displaying), I'd look at DateJS.