0

Hi am making some time calculation in jquery. Do you think am using the best way?

<table width="100%" border="0" cellpadding="0">
    <tr>
        <td>Departure Time</td>
        <td>Arrival Time</td>
        <td>Difference</td>
    </tr>
    <tr>
        <td><input name="departure" type="text" class="std1" id="departure"  size="10" alt="time"/></td>
        <td><input name="arrival" type="text" class="std1" id="arrival" size="10" alt="time"/></td>
        <td><input name="duration" type="text" class="std" id="duration" size="10" readonly="readonly" alt="time"/></td>
    </tr>
</table>


function hour2mins(timestr) {
    var spltd = timestr.split(":");
    if (spltd.length == 2) {
        return parseInt(parseInt(spltd[0] * 60) + parseInt(spltd[1]));
    } else {
        return false;
    }
}

function mins2hour(instr) {
    var hourstr = parseInt(instr / 60);
    if (hourstr.toString().length == 1) {
        hourstr = "0" + (hourstr + '');
    }
    var minstr = parseInt(instr % 60);
    if (minstr.toString().length == 1) {
        minstr = "0" + (minstr + '');
    }
    return hourstr + ':' + minstr;
}

function tdiff(t1, t2) {
    var t1 = hour2mins(t1);
    var t2 = hour2mins(t2);
    var ret = mins2hour(parseInt(t2 - t1));
    if (t2 < t1) {
        ret = mins2hour(parseInt(parseInt(t2 + 1440) - t1));
    }
    return ret;
}

$(function() {
    $("input.std1").keyup(function(b) {
        $("#duration").val(tdiff($("#departure").val(), $("#arrival").val()));
    });
});

link : http://jsfiddle.net/xmQD7/1/

2

1 Answer 1

1

Your code won't work for the following input: "07:09", "07:07". The problem is with your parseInt statement.

You should always pass in 10 as the second parameter, so that it's parsed as a decimal value.

    return parseInt(parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10));

Also, you don't need to wrap the addition of two parsed integers in a parseInt, so that would be just

    return parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10);

In mins2hour, you don't need a parseInt here:

var hourstr = parseInt(instr / 60);

and here:

var minstr = parseInt(instr % 60);

I'm guessing you wanted a string as this point (as your var name suggests), so that should have been

var hourstr = "" + (instr / 60);

var minstr = "" + (instr % 60);

There are a few more unnecessary uses of parseInt in your code. I suggest you read the documentation on parseInt - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Not the answer you're looking for? Browse other questions tagged or ask your own question.