Subtract two times and display the result in third textbox automatically

How would I check time difference from two text-boxes and show the result in third textbox in Javascript?

Two times are in 12 hours format

.

I am using this JavaScript code:

 function calculateTime() {

        var valuestart = $("[id$=TextBox3]").pickatime({ interval: 1 }).val();
        var valuestop = $("[id$=TextBox4]").pickatime({ interval: 1 }).val();


        var timeStart = new Date("01/01/2010 " + valuestart);
        var timeEnd = new Date("01/01/2010 " + valuestop);

        var difference = timeEnd - timeStart;
        var diff_result = new Date(difference);

        var hourDiff = diff_result.getHours();

        document.getElementById("TextBox2").innerHTML = hourDiff;        

   }
    $("select").change(calculateTime);
    calculateTime();

Is there is no way to do the above ?

The following script calculates the time between a start and end time in am/pm format. It is more complicated than your own script as it contains validation for each input covering out of range entries, non-number entries and start times after end time errors. The output is in total minutes and in xHr yMin format. No doubt you can adapt this to your own needs. Insert the script just above the </body> tag on your page.

<script type="text/javascript"> 
var F=document.ff2;
var msgObj=document.getElementById("msg");
function calc()
 { var totStartMin, totEndMin, elapsedT, elapsedHrs, eHr, eMin;     
   totStartMin=getTime("startAmpm","Start","startHr", "startMin");
   if(totStartMin===false){return; }
   totEndMin=getTime("endAmpm","End","endHr", "endMin");
   if(totEndMin===false){return; }
   if(totStartMin > totEndMin){ msgObj.innerHTML="End time must be after start time"; clear(); return; }   
   elapsedT=totEndMin-totStartMin;
   F.elapsedTimeMin.value=""+elapsedT+" min"; 
   elapsedHrs=elapsedT/60;
   eHr=parseInt(elapsedHrs);
   eMin=Math.round((elapsedHrs-eHr)*60);
   F.elapsedTimeHrs.value=""+eHr+"hr "+eMin+"min";
   // console.log("elapsedHrs= "+elapsedHrs+" eHr= "+eHr+" eMin= "+eMin+"");     
   // console.log("totEndM= "+totEndMin+" totStartMin= "+totStartMin+" elapsedT= "+elapsedT+"");
  }
 // -------------------
  function getTime(am_pm,startOrEnd,Hr,Min)
   { var Hx, Mx;
     if(F[am_pm].value.length===0){msgObj.innerHTML="Please select "+startOrEnd+" time AM or PM"; clear(); return false; }
     Hx=Number(F[Hr].value);
     if(isNaN(Hx)){msgObj.innerHTML=""+startOrEnd+" Hour must be a number"; clear(); return false; }  
     if(Hx<0 || Hx>12){msgObj.innerHTML=""+startOrEnd+" Hour is out of range"; clear(); return false; } 
     Mx=Number(F[Min].value); 
     if(isNaN(Mx)){msgObj.innerHTML=""+startOrEnd+" Minute must be a number"; clear(); return false; }  
     if(Mx<0 || Mx>59){msgObj.innerHTML=""+startOrEnd+" Minute is out of range"; clear(); return false; }   
     return 60*(Number(F[Hr].value)+Number(F[am_pm].value))+Number(F[Min].value); 
   } 
 // ------
   function clear(){ setTimeout(function(){msgObj.innerHTML="";},4000); }
//  
</script>

You will find a working copy of the program at the following link JSFiddle

2 Likes

[quote=“Kusum_Bera, post:1, topic:228717, full:true”]
How would I check time difference from two text-boxes and show the result in third textbox in Javascript?[/quote]

After putting both times in as dates, you would get the time from each (in milliseconds). The difference between the two is then easy to calculate and can then be used for the time between them.

Beware! What happens when a night shift is in at 11:00 PM and leaves at 7:00 AM? There be dragons.

And before someone else says it, what happens when a contractor is called out at 2:30 AM just before daylight savings is rolled back, and leaves 40 minutes later at at 2:10 AM? Or even worse, leaves two hours later at 3:30 AM?

It doesn’t have to be that extreme either. All night-shift know the horror of seeing one less hour on their pay stub than should be there.

Good point Paul, you could have a date as an input to cover the 2-day scenario. Adding daylight saving changes seems a bit extreme.

Dates for a 2-day scenario are certainly good.

Converting the date/time to a date object will deal with most daylight savings and leap year issues. Anything else can be dealt with by management, such as by using different times so that the correct resulting work time is in place.

1 Like

What is the use of this Number(F[am_pm].value) ?

Here we are adding zero hours if the time is AM and 12 hours if the time is PM. for instance 1:00PM is, as you know, 1+12=13 hours. The whole formula takes values from the various input elements, turns them into minutes, and then uses the minutes for the start time and then end time to calculate the elapsed time.
60 x ( number of hours + 0 or 12 hours depending on AM or PM) + number of minutes.

The F is a short cut to the form holding all of the input elements. F=document.ff2;
F[am_pm].value reads the value from the form using the am_pm variable passed by the function getTime(), which in turn has been passed by the function calc(). The sequence of events for the start time am_pm component is:
totStartMin=getTime("startAmpm", ........
getTime(am_pm, ........
Number(F[am_pm].value)
The startAmpm variable is the name of the start AM-PM radio button pair for the start time in the form.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.