How can I calculate the difference between two times that are in 24 hour format?

You can just subtract the hours right away doing it this way

var valuestart = $("select[name="timestart"]").val();
var valuestop = $("select[name="timestop"]").val();

//create date format          
var timeStart = new Date("01/01/2007 " + valuestart).getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();

var hourDiff = timeEnd - timeStart;             

Here’s the working fiddle http://jsfiddle.net/VnwF7/4/

UPDATE – to calculate if we are including the next day. Just add the following if block

 if (hourDiff < 0) {
    hourDiff = 24 + hourDiff;
 }

http://jsfiddle.net/gfvhqat9/

Leave a Comment