Add 2 times together JavaScript

前端 未结 4 1653
轮回少年
轮回少年 2020-12-21 12:39

Looking to add time together within javascript.

I have never written any javascript, and as such am struggling with the way to progress.

I have got to add

4条回答
  •  执念已碎
    2020-12-21 13:03

    For add array of time-format strings (including seconds and without counting days).

    For example:

    Input: times = ['00:00:10', '00:24:00']

    Output 00:24:10

    // Add two times in hh:mm:ss format
    function 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)
    }
    

提交回复
热议问题