How can I humanize this complete duration in moment.js / javascript

后端 未结 4 1928
遇见更好的自我
遇见更好的自我 2020-12-03 15:05

I have a \'time remaining\' counter in place for file uploads. The remaining duration is calculated and converted into milliseconds like so:

var elapsedTime         


        
4条回答
  •  不知归路
    2020-12-03 15:52

    I think your best bet would be something like this:

    function humanize(time){
        if(time.years   > 0){   return time.years   + ' years and '     + time.months   + ' months remaining';}
        if(time.months  > 0){   return time.months  + ' months and '    + time.days     + ' days remaining';}
        if(time.days    > 0){   return time.days    + ' days and '      + time.hours    + ' hours remaining';}
        if(time.hours   > 0){   return time.hours   + ' hours and '     + time.minutes  + ' minutes and ' + time.seconds + ' seconds remaining';}
        if(time.minutes > 0){   return time.minutes + ' minutes and '   + time.seconds  + ' seconds remaining';}
        if(time.seconds > 0){   return time.seconds + ' seconds remaining';}
        return "Time's up!";
    }
    

    Alternatively, you could use this function:

    function humanize(time){
        var o = '';
        for(key in time){
            if(time[key] > 0){
                if(o === ''){
                    o += time[key] + ' ' + key + ' ';
                }else{
                    return o + 'and ' + time[key] + ' ' + key + ' remaining';
                }
            }
        }
        return o + 'remaining';
    }
    

    It returns "x , for the 2 greatest values. (Or only seconds in the last case.

提交回复
热议问题