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

后端 未结 4 1913
遇见更好的自我
遇见更好的自我 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:37

    My HumanizeDuration.js library sounds like exactly what you want:

    humanizeDuration(1);         // "1 millisecond"
    humanizeDuration(3000);      // "3 seconds"
    humanizeDuration(2012);      // "2 seconds, 12 milliseconds"
    humanizeDuration(97320000);  // "1 day, 3 hours, 2 minutes"
    

    Looks like my answer's a bit late, but maybe it'll help others looking at this question!

    0 讨论(0)
  • 2020-12-03 15:38

    I ended up being happy with date-fns' formatDistanceToNow. You can add that function without having to add the whole library like moment.js

    0 讨论(0)
  • 2020-12-03 15:46

    You should give a try on this plugin: moment-duration-format

    Its syntax is very convenient:

    var moment = require('moment');
    require("moment-duration-format");
    moment.duration(32832, "seconds").format("h [hrs]: m [min]: s [sec]")
    // => 9 hrs: 7 min: 12 sec" 
    
    0 讨论(0)
  • 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 <time> and y <time> remaining", for the 2 greatest values. (Or only seconds in the last case.

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