elynoy
elynoy

Reputation: 1

Time difference between 2 hours

I have beem looking for a code like this for a few days now. I did search a lot on the forum and found a bunch of threads about what I need but I couldn't get them to work (I have 0 expericnce in JS). The code below does what I need, in a way. It gives a negative value if the start time is, for example, 21:00 and the end time is 09:00.

Can anyone help me set it to positive? (I think it's related to beeing one day before, not sure thought).

<input type="time"  id="start" value="21:00" >
<input type="time" id="end" value="09:00" >

<input id="diff">


<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;

document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};


function diff(start, end) {
    start = document.getElementById("start").value; //to update time value in each input bar
    end = document.getElementById("end").value; //to update time value in each input bar
    
    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);

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

setInterval(function(){document.getElementById("diff").value = diff(start, end);}, 1000); //to update time every second (1000 is 1 sec interval and function encasing original code you had down here is because setInterval only reads functions) You can change how fast the time updates by lowering the time interval
</script>

PS: I found this code in here Difference between two html time inputs

Thanks in advance, eLy

Upvotes: 0

Views: 166

Answers (1)

Song
Song

Reputation: 750

There are 2 possible solutions based on your requirement. Start: 11AM, End: 9AM

If you want the output to be 2 hours,

var diff = Math.abs(endDate.getTime() - startDate.getTime());

If you want the output to be 22 hours,

var diff = endDate.getTime() - startDate.getTime();
    if (diff < 0) {
        diff += 24 * 1000 * 60 * 60;
    }

Upvotes: 1

Related Questions