Cross Vander
Cross Vander

Reputation: 2177

Javascript Calculate Time including over night

I have create code for calculating between 2 time which result in minutes. It works fine if no overnight hour (example: 10:00 - 12:00, 14:00 - 16:00) the problem comes when I fill it with 23:00 and 01:00 (11 pm to 1 am), it return minus and count backward. You can see my code at snippet below.

Anyone know how to count it normally if there's an overnight? Or it's not possible if there's no date?

function parseTime(s) {
    var c = s.split(':');
    return (parseInt(c[0]) * 60) + parseInt(c[1]);
}
function getTotalMin(x)
{
    var awal = document.getElementById("awaljkab").value;
    var akhir = document.getElementById("akhirjkab").value;
    var selisih = parseTime(akhir) - parseTime(awal);
    x.value = String(selisih);
}
<!-- input clock as HH:mm ; example: 10:00 -->
<input type="text" class="form-control timepicker" name="startjkab" id="awaljkab" />
<input type="text" class="form-control timepicker" name="finishjkab" id="akhirjkab" />
<input type="text" class="form-control" name="lamajkab" onfocus="getTotalMin(this);" readonly="readonly" />

Upvotes: 0

Views: 313

Answers (2)

LostMyGlasses
LostMyGlasses

Reputation: 3144

Before calculating selisih you should check if the second hour is smaller than the first one:

if (akhir < awal) akhir += 24 * 60;

That way you ensure that akhir represents the following day. After that, you can calculate selih the way you did.

Upvotes: 2

suvroc
suvroc

Reputation: 3062

You can simply add 24 hours to second value if it is less than first one

var to = parseTime(akhir);
var from = parseTime(awal);
var selisih;
if (to < from)
{
    selisih = 24*60 + to - from;
} else {
    selisih = to - from;
}

http://jsfiddle.net/Lse3sk44/1/

Upvotes: 1

Related Questions