There were a few old solutions, most using jQuery, on adding multiple durations. I didn't find them to work correctly, so I wrote this one below. I'm not the best at JS, so I thought some input would be helpful on whether there is any issue with this script or a more efficient way to achieve the same result. I'm basically looking to add an array of times together for a total time, displayed correctly with two digits for the minutes and seconds. If nothing else, maybe this will help someone else.
var Playlist = ["5:00:00", "7:00", ":05"];
function TimeAdd(array) {
let h = 0;
let m = 0;
let s = 0;
for (let i = 0; i < Playlist.length; i++) {
let timeArray = array[i].split(":");
if(timeArray.length == 3){
h += parseInt(timeArray[0]);
m += parseInt(timeArray[1]);
s += parseInt(timeArray[2]);}
if(timeArray.length == 2 && timeArray[0]!==""){
m += parseInt(timeArray[0]);
s += parseInt(timeArray[1]);}
if(timeArray.length == 1){
s += parseInt(timeArray[0]); }
if(timeArray[0]==""){
s += parseInt(timeArray[1]);}
}
let time = s + (m * 60) + (h * 3600);
let hoursDec = time / 60 / 60;
let hours = Math.trunc(hoursDec);
let minutesDec = (hoursDec - hours) * 60;
let minutes = Math.trunc(minutesDec);
let seconds = Math.round((minutesDec - minutes) * 60);
console.log(hours + ":" + minutes.toLocaleString(undefined, {minimumIntegerDigits: 2}) + ":" + seconds.toLocaleString(undefined, {minimumIntegerDigits: 2}));}
question from:
https://stackoverflow.com/questions/66052666/adding-multiple-durations-in-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…