Jquery - Calculate the time sheet hours

Viewed 273

I am developing a time sheet project but having issue with calculating between start time, end time.

Basically, what I want the result to display is (4.5 hours) instead of 4.7 based on

start time: 7:30am, end time 12:00

<td><input type="time" class="dataInput" id="sMon" onchange="checkHoursTyped(this);SumHours();calTotalHours();" /></td>
<td><input class="dataInput" id="fMon" onchange="checkHoursTyped(this);SumHours();calTotalHours();"/></td>

function SumHours(){
    var monStart = 0;
    var monFinish = 0;

    monStart = Number($("#sMon").val().replace(/:/g,"."));
    monFinish = Number($("#fMon").val().replace(/:/g,"."));

    var workedHoursM = monFinish -= monStart;

    $("#hoursMon").val(workedHoursM);
}
2 Answers

The issue with your code is that you are converting 7:30 to 7.3 and treating the minutes components as if they were decimal components, which they are not (they are fractions of a 60th, corresponding to one hour). One approach here is to use regex to isolate the minutes component, and then convert it back to hours.

function SumHours() {
    var monStart = "7:30";
    var regexp = /(\d+):(\d+)/g;
    var match = regexp.exec(monStart);
    var start = match[1]*1.0 + (match[2] / 60.0);

    var monFinish = "12:00";
    var regexp = /(\d+):(\d+)/g;
    var match = regexp.exec(monFinish);
    var end = match[1]*1.0 + (match[2] / 60.0);

    var workedHoursM = end - start;
    console.log(workedHoursM);

    // in your actual code, make the following JQuery assignment
    //$("#hoursMon").val(workedHoursM);
}

SumHours();

This is another way :

function SumHours() {
  var smon = document.getElementById('sMon').value ;
  var fmon = document.getElementById('fMon').value ;
  var diff = 0 ;
  if (smon && fmon) {
    smon = ConvertToSeconds(smon);
    fmon = ConvertToSeconds(fmon);
    diff = Math.abs( fmon - smon ) ;
    console.log( 'time difference is : ' + secondsTohhmmss(diff) );
  }

  function ConvertToSeconds(time) {
    var splitTime = time.split(":");
    return splitTime[0] * 3600 + splitTime[1] * 60;
  }

  function secondsTohhmmss(secs) {
    var hours = parseInt(secs / 3600);
    var seconds = parseInt(secs % 3600);
    var minutes = parseInt(seconds / 60) ;
    return (minutes === 30) ? (hours + '.' + 5) : (hours + "hours : " + minutes + "minutes ");
  }
}
<td>
  <input type="time" class="dataInput" id="sMon" onchange="SumHours();" />
</td>

<td>
  <input type="time" class="dataInputt" id="fMon" onchange="SumHours();"/>
</td>

Related