我正在开发一个时间表项目,但是在开始时间和结束时间之间进行计算存在问题。
基本上,我希望显示的结果是(4.5小时),而不是4.7基于
开始时间:上午7:30,结束时间12:00
customButtons
答案 0 :(得分:3)
您的代码存在的问题是,您要将7:30
转换为7.3
,并将分钟分量视为十进制分量,而不是十进制分量(它们是60的分数,对应于一小时)。这里的一种方法是使用正则表达式隔离分钟部分,然后将其转换回小时。
function SumHours() {
var monStart = "7:30";
var regexp = /(\d+):(\d+)/g;
var match = regexp.exec(monStart);
var start = match[1]*1.0 + (match[2] / 60.0);
var monFinish = "12:00";
var regexp = /(\d+):(\d+)/g;
var match = regexp.exec(monFinish);
var end = match[1]*1.0 + (match[2] / 60.0);
var workedHoursM = end - start;
console.log(workedHoursM);
// in your actual code, make the following JQuery assignment
//$("#hoursMon").val(workedHoursM);
}
SumHours();
答案 1 :(得分:1)
这是另一种方式:
function SumHours() {
var smon = document.getElementById('sMon').value ;
var fmon = document.getElementById('fMon').value ;
var diff = 0 ;
if (smon && fmon) {
smon = ConvertToSeconds(smon);
fmon = ConvertToSeconds(fmon);
diff = Math.abs( fmon - smon ) ;
console.log( 'time difference is : ' + secondsTohhmmss(diff) );
}
function ConvertToSeconds(time) {
var splitTime = time.split(":");
return splitTime[0] * 3600 + splitTime[1] * 60;
}
function secondsTohhmmss(secs) {
var hours = parseInt(secs / 3600);
var seconds = parseInt(secs % 3600);
var minutes = parseInt(seconds / 60) ;
return (minutes === 30) ? (hours + '.' + 5) : (hours + "hours : " + minutes + "minutes ");
}
}
<td>
<input type="time" class="dataInput" id="sMon" onchange="SumHours();" />
</td>
<td>
<input type="time" class="dataInputt" id="fMon" onchange="SumHours();"/>
</td>