JCD JCD - 1 year ago 109
jQuery Question

Calculate numbers of hours from arrival time to completed time but

I have an online form where a user enters the arrival time, completed time, number of hours spent, the tax and then the rate. This works fine but if we're already entering the arrival and completed time, i should be able to get the hours automatically.


If a person arrives at a location at 11:00 am and leaves at 1:00 pm, the total should hours should be 2.00.

If a person arrives at a location at 5:30 pm and leaves at 7:30 pm, the total should hours should be 2.30.

I need to do this but I'm having issues:


<input type="text" name="start" id="start" placeholder="start"> <br>

<input type="text" name="end" id="end" placeholder="end" ><br>

<input type="text" name="hours" id="hours" placeholder="hours"><br>


$(document).ready(function() {

$("#start, #end").on("keydown keyup", function() {

function myFunction() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;

s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + "." + min.substring(0,2);
document.getElementById("hours").value = diff;



Answer Source

The issue you are having is negative numbers if the hours pass over 12:00.

Here is the code to fix it, this assumes the very next occurrence of the hour and not after. For example: 5:30 - 4:30 would be 11 hours, not 23 hours. It will think 5:30am - 4:30pm or 5:30pm - 4:30am (in your scenario it appears not to matter).

s = start.split(':');
e = end.split(':');
for(var i=0;i<s.length;i++) {
    s[i] = parseFloat(s[i]);
for(var i=0;i<e.length;i++) {
    e[i] = parseFloat(e[i]);
if(s[0] > e[0]) {
   s[0] = s[0] - 12;

Make sure numbers are parsed to float values just incase. Then if the start hour is greater than the end hour, subtract 12 from the start hour.

Fiddle: https://jsfiddle.net/e5cb7o0o/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download