首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Moment.js不能使简单的时间人性化

Moment.js不能使简单的时间人性化
EN

Stack Overflow用户
提问于 2017-10-24 15:59:22
回答 1查看 643关注 0票数 2

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

这是库的示例行为。

代码语言:javascript
复制
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

现在发生了什么,动量. is是如何解决的呢?

非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-24 16:13:42

默认的分钟相对时间阈值是45分钟。

duration.humanize的阈值定义了一个单元何时被认为是一分钟、一小时等等。例如,默认情况下,超过45秒被认为是一分钟,超过22个小时被认为是一天,依此类推。要改变这些断口,请使用moment.relativeTimeThreshold(unit, limit),其中单元为sssmhdM

如果您想要一个更高的临界点,请通过以下操作设置一个不同的值:

代码语言:javascript
复制
moment.relativeTimeThreshold('m', 60);

代码语言:javascript
复制
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()
]);
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

JSFiddle

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46915080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档