简体   繁体   中英

Javascript - How can I work out the difference between two given times? (hours-minutes)

I have two sets of 'select' elements where the user can enter in two times. It looks like this:

Start:
[hour] [minute] [meridian]

End:
[hour] [minute] [meridian]

I'm trying to take those times and figure out the difference. So I can then output:

Difference: 1.25 HRS

The decimal format, as you probably know, means 1 hour and 15 minutes. There's also a checkbox the user can click which, if selected, will take away 30 minutes. Here's what my current code looks like:

var startHours     = parseInt($start.find('.times:eq(0)')[0].value);
var startMinutes   = parseInt($start.find('.times:eq(1)')[0].value);
var startMeridian  = $start.find('.times:eq(2)')[0].value

if (startMeridian == 'PM')
   startHours += 12;

var finishHours    = parseInt($finish.find('.times:eq(0)')[0].value);
var finishMinutes  = parseInt($finish.find('.times:eq(1)')[0].value);
var finishMeridian = $finish.find('.times:eq(2)')[0].value

if (finishMeridian == 'PM')
   finishHours += 12;

// compute the difference
var completeHours   = finishHours - startHours;
var completeMinutes = finishMinutes - startMinutes;
var newTime = 0;

if (completeHours < 0 || completeMinutes < 0)
   newTime = '0.0';
else
   newTime = completeHours + '.' + completeMinutes; 

var hadBreak = $parent.parents('tr').next('tr').find('.breakTaken')[0].checked;

if (hadBreak)
{
   time    = newTime.split('.');
   hours   = time[0];
   minutes = time[1];

   minutes = minutes - 30;

   if (minutes < 0)
   {
      minutes = 60 - (minutes * 1);
      hours   = hours - 1;
   }

   newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
}

$parent.parents('tr').next('tr').find('.subtotal')[0].innerHTML = newTime;

total += parseFloat(newTime);

It's failing... What am I doing wrong?

To save you some hassle, I would recommend using the Date object, which is very convenient:

var startDate = new Date(year, month, date, hour, minute, second, millisecond);
var endDate = new Date(year, month, date, hour2, minute2, second2, millisecond2);
// You can skip hours, minutes, seconds and milliseconds if you so choose

var difference = endDate - startDate; // Difference in milliseconds

From there you can calculate the days, hours and minutes that passed between those two dates.

The line

 newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;

is wrong - minutes might be 15, but you want it to print out the fraction. Hence you need:

 var MinutesDisplay = minutes/60*100;
 newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM