What I want is a function that takes two string parameters of the form
hh:mm in 24h format and calculates the difference.
You really don't have to convert the time parts into numbers if you are
doing a subtraction operation on them. Javascript will automatically
convert the strings into numbers for you (type coercion), since the "-"
operator doesn't apply to strings. Of course, if you later changed the
code to use the "+" operator you would run into unexpected results
since the numbers would be concatenated rather than added, so having a
parseInt(sNum, 10) for clarity isn't a bad idea.
I'm not sure why you are only working with hours and minutes, I can
only assume you are somehow guaranteed that they will always be from
the same day. Depending on how robust this code needs to be, you may
also want to take into consideration the effects of daylight savings
time. If the two times being subtracted include a DST change, the
results may not be what you expect to see.
The JavaScript Date object applies to the client computer, and so using
the Date object and specifying the full date and subtracting Date
objects would be one approach to handling the DST issue. Documentation
for the Date object can be found at
http://msdn.microsoft.com/library/en-us/script56/html/js56jsobjdate.asp.
The example below uses the HH:SS format as you specified, although it
could be modified to work with a full date format:
function getHourMinDifInMinutes(sHourMin1, sHourMin2) {
var dt1 = getHourMinAsDate(sHourMin1);
var dt2 = getHourMinAsDate(sHourMin2);
var iDif_ms = dt2 - dt1;
return(iDif_ms / 1000 / 60);
} //getHourMinDifInMinutes
function getHourMinAsDate(sHourMin) {
var aHourMin = sHourMin.split(":");
//new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]])
var dt = new Date(1900, 0, 1, aHourMin[0], aHourMin[1]);
return(dt);
} //getHourMinAsDate
alert(getHourMinDifInMinutes("02:09", "03:09"));