我在军事(24小时)时间里有几天的“时钟输入”和“时钟输出”条目是普通数字。
Clock In | Clock Out
--------------------
1020 | 1555
1116 | 1857
1049 | 1204
我已经手动确定此人已经 14小时31分钟。我有一个HTML页面,在一个类中包含很多这些条目,所以我使用以下代码在Javascript中获取它们:
$('.clockin').each(function() {clockinsum += +$(this).text()||0;});
$('.clockout').each(function() {clockoutsum += +$(this).text()||0;});
我不确定从哪里开始,或者这是否是正确的开始方式。有没有办法让Javascript / jQuery从一堆条目中计算小时和分钟?
答案 0 :(得分:1)
你需要一些东西来判断时差。
在JavaScript中,您总是以毫秒为单位工作,因此找到每个开始和结束时间之间的毫秒差异,复合它们并使用该时间来计算花费的时间:
var list = [
["1020", "1555"],
[1116, 1857],
[1049, "1204"],
];
/**
* Difference between two times in milliseconds
*
* @param {(number | string)} start
* @param {(number | string)} end
* @returns {number}
*/
function getTimeDifference(start, end) {
var d1 = new Date(0);
d1.setHours(parseInt(start.toString().substr(0, 2), 10));
d1.setMinutes(parseInt(start.toString().substr(2, 2), 10));
var d2 = new Date(0);
d2.setHours(parseInt(end.toString().substr(0, 2), 10));
d2.setMinutes(parseInt(end.toString().substr(2, 2), 10));
return d2.getTime() - d1.getTime();
}
//figure how long this guy has worked:
var compiledTime = 0;
for (var index = 0; index < list.length; index++) {
compiledTime += getTimeDifference(list[index][0], list[index][1]);
}
//At this point "compiledTime" contains the milliseconds the guy has worked
//Let's print it nice and pretty
var compiledTimeDate = new Date(compiledTime);
alert("Hours: " + compiledTimeDate.getHours() + "\n" +
"Minutes: " + compiledTimeDate.getMinutes() + "\n" +
"Seconds: " + compiledTimeDate.getSeconds() + "\n" +
compiledTimeDate.getHours() + ':' + compiledTimeDate.getMinutes() + ':' + compiledTimeDate.getSeconds());
//From here you can use the Date object methods to do whatever
答案 1 :(得分:1)
如果您已经在数组中输入和输出时钟或者可以将它们放入数组中,您可以进行一些简单的数学运算。
var clockIn = [1555, 1857, 1204];
var clockOut = [1020, 1116, 1049];
var timeWorked = 0;
//assuming for every clock in there is a clock out
for(var i = 0; i<=clockOut.length-1; i++){
timeWorked = timeWorked+(clockIn[i] - clockOut[i]);
}
console.log(timeWorked);
这将返回1431,相当于14小时31分钟。