【问题标题】:Moment.js doesn't humanize simple hoursMoment.js 不会将简单的时间人性化
【发布时间】:2017-10-24 15:59:22
【问题描述】:

我在一个网站中使用 moment.js,我必须在其中显示不同时期之间的持续时间。我得到毫秒持续时间,除以 3600 * 1000 后,我得到十进制小时格式。我正在尝试使用moment.js 的人性化方法,但不够准确。

这是库的示例行为

moment.duration(0.5, 'hours').humanize();   // returns '30 minutes' OK
moment.duration(0.1, 'hours').humanize();   // returns '6 minutes' OK
moment.duration(0.8, 'hours').humanize();   // returns 'an hour' BAD
moment.duration(0.7, 'hours').humanize();   // returns '42 minutes' OK
moment.duration(0.72, 'hours').humanize();  // returns '43 minutes' OK
moment.duration(0.73, 'hours').humanize();  // returns '44 minutes' OK
moment.duration(0.74, 'hours').humanize();  // returns '44 minutes' OK
moment.duration(0.75, 'hours').humanize();  // returns 'an hour' BAD

发生了什么,moment.js-way 是如何解决的?

非常感谢。

【问题讨论】:

    标签: javascript time momentjs


    【解决方案1】:

    Relative Time Threshold 的默认分钟数是 45 分钟。

    duration.humanize 具有定义何时将单位视为一分钟、一小时等的阈值。例如,默认情况下,超过 45 秒被认为是一分钟,超过 22 小时被认为是一天等等。要更改这些截止值,请使用moment.relativeTimeThreshold(unit, limit),其中单位是sssmhdM 之一。

    如果您想要更高的截止点,请通过以下方式设置不同的值:

    moment.relativeTimeThreshold('m', 60);
    

    moment.relativeTimeThreshold('m', 60);
    
    console.log([
      moment.duration(0.5, 'hours').humanize(),
      moment.duration(0.1, 'hours').humanize(),
      moment.duration(0.8, 'hours').humanize(),
      moment.duration(0.7, 'hours').humanize(),
      moment.duration(0.72, 'hours').humanize(),
      moment.duration(0.73, 'hours').humanize(),
      moment.duration(0.74, 'hours').humanize(),
      moment.duration(0.75, 'hours').humanize()
    ]);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

    JSFiddle

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多