Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

Adding Multiple Durations in Javascript

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would just convert them all to seconds using reduce.

var playlist = ["5:00:00", "7:00", "5"];

function getSeconds(time) {
  var parts = ("0:0:" + time).split(":").slice(-3)
  return parseInt(parts[0], 10) * 3600 + parseInt(parts[1], 10) * 60 + parseInt(parts[2], 10);
}

var totalSeconds = playlist.reduce((acc, ts) => acc + getSeconds(ts),0);

function secondsToHms(secs) {
    var h = ("0" + Math.floor(secs / 3600)).substr(-2);
    var m = ("0" + Math.floor(secs % 3600 / 60)).substr(-2);
    var s = ("0" + Math.floor(secs % 3600 % 60)).substr(-2);
    return h + ":" + m + ":" + s; 
}

console.log(secondsToHms(totalSeconds));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...