wawanopoulos - 8 months ago 57

Javascript Question

I am searching an easy way to sum hours and minutes in javascript to produce a total value :

`var json1 = {`

hour : "8",

minutes : "15"

};

var json2 = {

hour : "8",

minutes : "45"

};

Expected output :

`var total = "17h00";`

Answer Source

```
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;
}
```