Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the hours between two times with jquery?

I am trying to calculate the hours between two times.

Below is where I am currently but this code fails in two ways.

1). I need .Hours to output time in decimal.

(e.g one and half hours should output 1.5 and 15mins should be 0.25).

2). Calculation currently does not treat values for time as time.

(e.g 23:00 to 2:00 should equal 3 and NOT -21 as currently).


HTML

<input class="Time1" value="10:00" />
<input class="Time2" value="12:00" />
<input class="Hours" value="0" />

JQUERY

 $(function () {
     function calculate() {
         var hours = parseInt($(".Time2").val().split(':')[0], 10) - parseInt($(".Time1").val().split(':')[0], 10);
         $(".Hours").val(hours);
     }
     $(".Time1,.Time2").change(calculate);
     calculate();
 });

http://jsfiddle.net/44NCk/

like image 462
DreamTeK Avatar asked Feb 14 '14 11:02

DreamTeK


2 Answers

Easy way is if you get a negative value, add 24 hours to it and you should have your result.

var hours = parseInt($(".Time2").val().split(':')[0], 10) - parseInt($(".Time1").val().split(':')[0], 10);

// if negative result, add 24 hours
if(hours < 0) hours = 24 + hours;

Demo: http://jsfiddle.net/44NCk/1/

Getting the minutes as a decimal involves a bit more as you can see in thsi fiddle: http://jsfiddle.net/44NCk/2/

function calculate() {
     var time1 = $(".Time1").val().split(':'), time2 = $(".Time2").val().split(':');
     var hours1 = parseInt(time1[0], 10), 
         hours2 = parseInt(time2[0], 10),
         mins1 = parseInt(time1[1], 10),
         mins2 = parseInt(time2[1], 10);
     var hours = hours2 - hours1, mins = 0;

     // get hours
     if(hours < 0) hours = 24 + hours;

     // get minutes
     if(mins2 >= mins1) {
         mins = mins2 - mins1;
     }
     else {
         mins = (mins2 + 60) - mins1;
         hours--;
     }

     // convert to fraction of 60
     mins = mins / 60; 

     hours += mins;
     hours = hours.toFixed(2);
     $(".Hours").val(hours);
 }
like image 158
techfoobar Avatar answered Oct 08 '22 22:10

techfoobar


function timeobject(t){
  a = t.replace('AM','').replace('PM','').split(':');
  h = parseInt(a[0]);
  m = parseInt(a[1]);
  ampm = (t.indexOf('AM') !== -1 ) ? 'AM' : 'PM';
  return {hour:h,minute:m,ampm:ampm};
}

function timediff(s,e){
  s = timeobject(s);
  e = timeobject(e);
  e.hour = (e.ampm === 'PM' &&  s.ampm !== 'PM' && e.hour < 12) ? e.hour + 12 : e.hour;
  hourDiff = Math.abs(e.hour-s.hour);
  minuteDiff = e.minute - s.minute;

  if(minuteDiff < 0){
    minuteDiff = Math.abs(60 + minuteDiff);
    hourDiff = hourDiff - 1;
  }

  return hourDiff+':'+ Math.abs(minuteDiff);
}

difference = timediff('09:10 AM','12:25 PM');  // output 3:15
difference = timediff('09:05AM','10:20PM');  // output 13:15
like image 29
rk3263025 Avatar answered Oct 08 '22 23:10

rk3263025