I have a 'time remaining' counter in place for file uploads. The remaining duration is calculated and converted into milliseconds like so:
var elapsedTime = e.timeStamp - timestarted;
var speed = e.loaded / elapsedTime;
var estimatedTotalTime = e.totalSize / speed;
var timeLeftInSeconds = (estimatedTotalTime - elapsedTime) / 1000;
I then build an array which I intend to build into a humanized string. The array is as follows:
var time = {
years : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').years()),
months : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').months()),
days : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').days()),
hours : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').hours()),
minutes : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').minutes()),
seconds : Math.round(moment.duration(timeLeftInSeconds, 'milliseconds').seconds())
};
This all works perfectly and if I output a string representation of this data like so:
console.log(time.years + ' years, ' + time.months + ' months, ' + time.days + ' days, ' + time.hours + ' hours, '+ time.minutes + ' minutes, ' + time.seconds + ' seconds');
I it returns a nice simple stream of remaining time like so:
0 years, 0 months, 0 days, 0 hours, 1 minutes, 7 seconds
What I now need to do is humanize this output so that the string is built dependent on the time remaining. e.g
- 2 years and 3 months remaining
- 1 hour, 32 minutes and 41 seconds remaining
- 7 seconds remaining
- 3 minutes 46 seconds remaining
- 6 seconds remaining
etc...etc...
Now I know that moment.js has the abiility to automatically humanize durations which works fine for single values but this can have multiple possible values ( hours/minutes/seconds etc)
How can I go about humanizing this data either with moment.js or by manually building the string?
Thanks in advance.
See Question&Answers more detail:
os