我正在寻找一种简单的方法来在javascript中总结小时和分钟以产生总价值:
var json1 = {
hour : "8",
minutes : "15"
};
var json2 = {
hour : "8",
minutes : "45"
};
预期产出:
var total = "17h00";
答案 0 :(得分:1)
var totalH;
var totalM;
addTimes = function(timeMap) {
// First simply adding all of it together, total hours and total minutes
for (var x in timeMap) {
totalH += parseInt(timeMap[x].hour, 10);
totalM += parseInt(timeMap[x].minutes, 10);
}
// If the minutes exceed 60
if (totalM >= 60) {
// Divide minutes by 60 and add result to hours
totalH += Math.floor(totalM / 60);
// Add remainder of totalM / 60 to minutes
totalM = totalM % 60;
}
return totalH + "h" + totalM;
}
答案 1 :(得分:1)
只需在Chrome控制台中复制粘贴并查看漂亮的结果
var json1 = { hour : "8", minutes : "15" };
var json2 = { hour : "8", minutes : "45" };
function get_add_two_times(json1, json2) {
hr = parseInt(json1.hour) + parseInt(json2.hour);
mn = parseInt(json1.minutes) + parseInt(json2.minutes);
final_hr = hr + Math.floor(mn/60);
final_mn = mn%60;
final_mn = (final_mn < 10) ? '0' + final_mn : final_mn;
return final_hr + 'h' + final_mn;
}
get_add_two_times(json1,json2);
一些示例输出
var json1 = {hour : "1", minutes : "15"};
var json2 = {hour : "02", minutes : "49"};
> "4h04"
var json1 = {hour : "12", minutes : "15"};
var json2 = {hour : "12", minutes : "49"};
> "25h04"
答案 2 :(得分:0)
这是一种功能性方法,假设你有一个时间数组
var times = [{
hour : "8",
minutes : "15"
},{
hour : "8",
minutes : "45"
}]
迭代次数,求和,然后格式化,然后加入字符串。
times.reduce(function(memo, t) { // sum the times
memo[0] += parseInt(t.hour, 10)
memo[1] += parseInt(t.minutes, 10)
if (memo[1] >= 60) {
memo[0] += ~~(memo[1]/60)
memo[1] = memo[1] % 60
}
return memo
}, [0, 0]).map(function(t) { // map to the desired format
if (t < 10) {
return '0' + t
}
return t
}).join('h') // => 17h00