can anyone tell me how to do sum of two time using javascript (momentjs) for exemple the sum of:
2:44:56 and 2:50:56
i tried that but doesnt work:
2:44:56 + 2:50:56
any suggestions please??
can anyone tell me how to do sum of two time using javascript (momentjs) for exemple the sum of:
2:44:56 and 2:50:56
i tried that but doesnt work:
2:44:56 + 2:50:56
any suggestions please??
You can do it like this. Use add method on moment object and pass your data.
let x = moment({
hours:'2',
minutes:'44',
seconds:'56'})
.add({
hours:'2',
minutes:'50',
seconds:'56' })
console.log(x)
or dynamically pass data
let time = {
hours: 2,
minutes:44,
seconds: 56
}
let time2 = {
hours: 2,
minutes:50,
seconds: 56
}
let y = moment(time)
.add(time2)
console.log(y)
One could add the seconds, then calculate the carry value and add that to the sum of minutes and so on. That can be easily done with reduce:
function sum(date1, date2){
date1 = date1.split(":");
date2 = date2.split(":");
const result = [];
date1.reduceRight((carry,num, index) => {
const max = [24,60,60][index];
const add = +date2[index];
result.unshift( (+num+add+carry) % max );
return Math.floor( (+num + add + carry) / max );
},0);
return result.join(":");
}
console.log(
sum("2:44:56" , "2:50:56" )
);
var t1 = moment('2:44:56', 'HH:mm:ss');
var t2 = '2:50:56';
var parsed_t2 = t2.split(':') // [2, 50, 56]
var r = t1.add({
hours: parsed_t2[0], // 2
minutes: parsed_t2[1], // 50
seconds: parsed_t2[2], // 56
});
split()
function effectively splitting our t2 into an array where we have [hours, minutes, seconds]
add()
method.moment() function takes hours, minutes, seconds as arguments and return a moment object which has a add() method that also can take hours, minutes, seconds as arguments and return total times.
Try addTimes(time1, time2)
function addTimes(time1, time2) {
let [hours1, minutes1, seconds1] = time1.split(':');
let [hours2, minutes2, seconds2] = time2.split(':');
return moment({ hours: hours1, minutes: minutes1, seconds: seconds1 })
.add({ hours: hours2, minutes: minutes2, seconds: seconds2 })
.format('h:mm:ss');
}
console.log(addTimes('2:44:56', '2:50:56'));
Good old JS solution:
var base = new Date(0);
var t1 = new Date(base);
var t2 = new Date(base);
t1.setUTCHours(2,45,50);
t2.setUTCHours(2,50,50);
var t = new Date(t1.getTime() + t2.getTime() - base.getTime());
result = t.getUTCHours() + ":" + t.getUTCMinutes() +":" + t.getUTCSeconds();
console.log(result);
Note that JS automatically converts time of the day to GMT timezone hence we need to use UTC version of time functions.