我有几天的军事(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 有没有办法计算这些条目的工作小时数和分钟数?
最佳答案
你需要一些东西来告诉时差。
在 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
关于javascript - 用 Javascript 计算军事时间以获得工作小时数和分钟数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43072415/