Formatting MomentJS duration above 24 hours

前端 未结 3 1309
面向向阳花
面向向阳花 2021-02-19 12:10

I would like to format a summed up total working hours e.g. 49.75 to this: 49:45.

When I use duration like this:

const         


        
相关标签:
3条回答
  • 2021-02-19 13:00

    I recommend you this answer.

    You can add a format for the duration, and it works for greater than 24 Hour.

    function(input) {
        input = input || '';
        var out = '';
        var dur = moment.duration(input, 'minutes');
        return dur.format('HH:mm:ss');
    };
    

    I hope it can help you!

    EDIT:

    This code uses duration-format plugin!

    0 讨论(0)
  • 2021-02-19 13:13

    If you are modifying one second at a time, it can be simplified quite a lot (parsing and updating).

    Inspiration lifted from this answer: https://stackoverflow.com/a/45629433/11121690

    incrementTime: (sectionKey, itemKey) => {
        const pad = (number) => `${number > 9 ? number : "0" + number}`;
        const timeString = STATS_DATA_UTIL.getByParts(sectionKey, itemKey);
        const parts = timeString.split(':');
        let uiSecs = parseInt(parts[2]);
        let uiMins = parseInt(parts[1]);
        let uiHrs = parseInt(parts[0]);
    
        uiSecs++;
        if (uiSecs === 60) {
            uiSecs = 0; uiMins++;
            if (uiMins === 60) uiMins = 0; uiHrs++;
        }
    
        const result = `${pad(uiHrs)}:${pad(uiMins)}:${pad(uiSecs)}`;
        STATS_DATA_UTIL.setByParts(sectionKey, itemKey, result);
    },
    
    0 讨论(0)
  • 2021-02-19 13:15

    I think you cannot use format but build it manually:

    var dur = moment.duration(49.75, 'hours');
    var hours = Math.floor(dur.asHours());
    var mins  = Math.floor(dur.asMinutes()) - hours * 60;
    var sec   = Math.floor(dur.asSeconds()) - hours * 60 * 60 - mins * 60;
    
    var result = hours + ":" + mins + ":" + ((sec > 9) ? sec : ("0"+sec));
    console.log(result); // 49:45:00
    

    Fiddle


    Hope someone will find more elegant way

    0 讨论(0)
提交回复
热议问题