我怎样才能在 moment.js/javascript 中人性化这个完整的持续时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14157341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:52:07  来源:igfitidea点击:

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

javascriptmomentjs

提问by gordyr

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
  • 还剩2年3个月
  • 还剩 1 小时 32 分 41 秒
  • 剩余 7 秒
  • 剩余 3 分 46 秒
  • 还剩 6 秒

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)

现在我知道 moment.js 具有自动人性化持续时间的能力,这对单个值工作正常,但这可以有多个可能的值(小时/分钟/秒等)

How can I go about humanizing this data either with moment.js or by manually building the string?

我如何使用 moment.js 或手动构建字符串来人性化这些数据?

Thanks in advance.

提前致谢。

采纳答案by Cerbrus

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.

"x <time> and y <time> remaining"对于 2 个最大值,它返回。(或者在最后一种情况下只有几秒钟。

回答by Evan Hahn

My HumanizeDuration.jslibrary sounds like exactly what you want:

我的HumanizeDuration.js库听起来正是您想要的:

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!

看起来我的回答有点晚了,但也许它会帮助其他人看这个问题!

回答by Hoang Le

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

你应该试试这个插件: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" 

回答by Dan Wood

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

我最终对 date- fns 的 formatDistanceToNow 感到满意。您可以添加该函数,而无需像 moment.js 那样添加整个库