Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Time Difference with JavaScript

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.

Format example: 10:00 & 12:30 need to give me: 02:30

Thanks!

like image 718
user1424332 Avatar asked May 29 '12 17:05

user1424332


1 Answers

Here is one possible solution:

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * 1000 * 60 * 60;
    var minutes = Math.floor(diff / 1000 / 60);

    // If using time pickers with 24 hours format, add the below line get exact hours
    if (hours < 0)
       hours = hours + 24;

    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}

DEMO: http://jsfiddle.net/KQQqp/

like image 127
VisioN Avatar answered Oct 19 '22 16:10

VisioN