Reputation: 11
I have two arrays of different time string.
startingTime: string["09:00:00", "5:50:00", "6:30:00"];
duration: string["0:15:00", "01:00:00", "01:00:00"];
I want to sum these arrays in final like
endingTime: string ["09:15:00", "6:50:00", "7:30:00"]
I'm building Single page application using angular 7,trying to use momentjs but not sure how to implement it. I would appreciate any help.
Upvotes: 1
Views: 1638
Reputation: 506
@Godwin Stanislaus Your code works fine for me except for an error, str.split() is not a function. However, appending +' ' to string solved that issue.
Below code returns sum of multiple time strings(HH:MM:SS)
var timedata=['00:00:08', '00:22:78', '02:22:01', '00:15:07'];
var total=this.sumTime(timedata);
console.log('total time spent', total);
sumTime(arr) {
var seconds:number=0;
var date = new Date(1970,0,1);
arr.forEach(element => {
var a = (element+'').split(":");
var sec = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
seconds=seconds+sec;
});
date.setSeconds(seconds);
var c = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
return c;
}
Upvotes: 0
Reputation: 22213
Try like this:
let seta = ["09:00:00", "5:50:00", "6:30:00"];
let setb = ["0:15:00", "01:00:00", "01:00:00"]
let totalArray = []
seta.forEach((time,index) => {
totalArray.push(this.addTimes([time,setb[index]))
});
addTimes(times) {
const z = (n) => (n < 10 ? '0' : '') + n;
let hour = 0
let minute = 0
let second = 0
for (const time of times) {
const splited = time.split(':');
hour += parseInt(splited[0]);
minute += parseInt(splited[1])
second += parseInt(splited[2])
}
const seconds = second % 60
const minutes = parseInt(minute % 60) + parseInt(second / 60)
const hours = hour + parseInt(minute / 60)
return z(hours) + ':' + z(minutes) + ':' + z(seconds)
}
Upvotes: 1
Reputation: 91
addTimes(start, end) {
var a = start.split(":");
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var b = end.split(":");
var seconds2 = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
var date = new Date(1970, 0, 1);
date.setSeconds(seconds + seconds2);
var c = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
return c;
}
addDurationToHours() {
let hours = ["09:00:00", "5:50:00", "6:30:00"];
let duration = ["0:15:00", "01:00:00", "01:00:00"];
let newArray = [];
hours.forEach( ( hour, index ) => {
newArray.push( this.addTimes(hour, duration[index]))
})
console.log ( newArray )
return newArray;
}
I referred Adding HH:MM:SS strings in Javascript for addTimes() method
Upvotes: 2