[英]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. 您可能知道,十进制格式表示1小时15分钟。 There's also a checkbox the user can click which, if selected, will take away 30 minutes. 用户还可以单击一个复选框,如果选中该复选框,将花费30分钟。 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: 为了节省您的麻烦,我建议使用Date对象,这非常方便:
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. 是错误的-分钟可能是15分钟,但您希望将其打印出来。 Hence you need: 因此,您需要:
var MinutesDisplay = minutes/60*100;
newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.