Add multiple DateTime Duration strings together using JavaScript to get total duration

前端 未结 4 1548
春和景丽
春和景丽 2021-01-16 07:36

I have an HTML Table used to generate a Calendar which shows TimeClock entries for each day a user has worked and clocked in and out of the system. Each day also shows the

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-16 07:57

    Try this:

    function hhmmssToSeconds(str)  {
        var arr = str.split(':').map(Number);
        return (arr[0] * 3600) + (arr[1] * 60) + arr[2];
    };
    
    function secondsToHHMMSS(seconds) {
        var hours = parseInt(seconds / 3600, 10),
            minutes = parseInt((seconds / 60) % 60, 10),
            seconds = parseInt(seconds % 3600 % 60, 10);
    
        return [hours, minutes, seconds].map(function (i) { return i.toString().length === 2 ? i : '0' + i; }).join(':');
    }
    

    Then:

    var t1 = hhmmssToSeconds('40:50:40'),
        t2 = hhmmssToSeconds('04:12:30');
    
    var result = secondsToHHMMSS(t1 + t2); // '45:03:10'
    

提交回复
热议问题