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

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" 

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!


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.