2

I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample

10:20 + 10:30 current output 0.10

10:20 + 10:30 I want the output to be 00.10

$(function () {
 function calculate() {
         time1 = $("#start").val().split(':'),
         time2 = $("#end").val().split(':');
         hours1 = parseInt(time1[0], 10), 
         hours2 = parseInt(time2[0], 10),
         mins1 = parseInt(time1[1], 10),
         mins2 = parseInt(time2[1], 10);
         hours = hours2 - hours1,
         mins = 0;
     if(hours < 0) hours = 24 + hours;
     if(mins2 >= mins1) {
         mins = mins2 - mins1;
     } else {
         mins = (mins2 + 60) - mins1;
     }

     // the result
     $("#hours").val(hours + ':' + mins);         
 }

});

also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?

Kaval Patel
  • 670
  • 4
  • 20
mxboy
  • 33
  • 4
  • Possible duplicate of [javascript format number to have 2 digit](https://stackoverflow.com/questions/8043026/javascript-format-number-to-have-2-digit) – Rajesh Oct 23 '17 at 06:34
  • For `NaN`, you can check `return isNaN(hours) ? '00' : ('0' + hours).slice(-2)` – Rajesh Oct 23 '17 at 06:36

3 Answers3

2

Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...

function calculate() {

    // Get time values and convert them to javascript Date objects.
    var time1 = new Date('01/01/2017 ' + $('#start').val());
    var time2 = new Date('01/01/2017 ' + $('#end').val());
    // Get the time difference in minutes. If is negative, add 24 hours.
    var hourDiff = (time2 - time1) / 60000;
    hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
    // Calculate hours and minutes.
    var hours = Math.floor(hourDiff/60);
    var minutes = Math.floor(hourDiff%60);
    // Set the result adding '0' to the left if needed        
    $("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}

Or even better, you can make the function independent of the DOM elements, so you can reuse it...

function calculate(startTime,endTime) {

    // Get time values and convert them to javascript Date objects.
    var time1 = new Date('01/01/2017 ' + startTime);
    var time2 = new Date('01/01/2017 ' + endTime);
    // Get the time difference in minutes. If is negative, add 24 hours.
    var hourDiff = (time2 - time1) / 60000;
    hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
    // Calculate hours and minutes.
    var hours = Math.floor(hourDiff/60);
    var minutes = Math.floor(hourDiff%60);
    // Return the response, adding '0' to the left of each field if needed.       
    return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}

// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
A. Iglesias
  • 2,625
  • 2
  • 8
  • 23
1

Add a function

function checkTime(i) {
if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
return i;

}

and call this function before displaying result

shiv keerthi
  • 32
  • 13
0

I propose you that :

    $(".calculator").on("change",function(){
    
    var isNegative = false;
    var hours = "00:00";
    var inputStart = $("#start").val();
    var inputEnd = $("#end").val();
    
    if(inputStart!="" && inputEnd != ""){
    // calculate only if the 2 fields have inputs

    // convert to seconds (more convenient)
     var seconds1 = stringToSeconds(inputStart);
     var seconds2 = stringToSeconds(inputEnd);
    
     var secondsDiff = seconds2 - seconds1;
    
     var milliDiffs = secondsDiff * 1000;
    
     if(milliDiffs < 0){
      milliDiffs = milliDiffs *-1;
      isNegative = true;
     }
    // Convert the difference to date
     var diff = new Date(milliDiffs);
    // convert the date to string
     hours = diff.toUTCString();
    // extract the time information in the string 00:00:00
     var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
     var arr = hours.match(regex);
     hours = arr[0];
   // Take only hours and minutes and leave the seconds
     arr = hours.split(":");
     hours=arr[0]+":"+arr[1];
    // put minus in front if negative
     if(isNegative){
      hours = "-"+hours;
     }
    // Show the result
     $("#hours").val(hours);  
    // Put back the inputs times in case there were somehow wrong
    // (it's the same process)
     var date1 = new Date(seconds1*1000);
     var str1 = date1.toUTCString();
     arr = str1.match(regex);
     hours = arr[0];
     arr = hours.split(":");
     hours=arr[0]+":"+arr[1];
    
     $("#start").val(hours);  
       // idem for time 2
     var date2 = new Date(seconds2*1000);
     var str2 = date2.toUTCString();
     arr = str2.match(regex);
     hours = arr[0];
     arr = hours.split(":");
     hours=arr[0]+":"+arr[1];
    
     $("#end").val(hours);  
    
    
    }
    
    });
    
    function timeElementToString(timeElement){
     var output = timeElement.toString();
     if(timeElement < 10 && timeElement >=0)
      output = "0"+output;
     else if(timeElement < 0 && timeElement >=-10)
      output = "-0"+Math.abs(output);
       
      return output;
    }
    
    function stringToSeconds(input){
     var hours = 0;
     var arr=input.split(":");
     if(arr.length==2){
      hours=parseInt(arr[0]);
      minutes=parseInt(arr[1]);
    
      if(isNaN(hours)){
    
                hours = 0;
            }
      if(isNaN(minutes)){
    
                minutes = 0;
            }
     }
     return hours*3600+60*minutes;
    }
        

  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>
PhilMaGeo
  • 551
  • 6
  • 8