[英]Moment.js how to use fromNow() to return everything in hours?
I've searching the moment.js docs and stackoverflow for a way to use the fromNow()
function but returning everything in hours. 我正在搜索moment.js文档和stackoverflow,以获得一种使用
fromNow()
函数但在几小时内返回所有内容的方法。
What I mean is: 我的意思是:
moment([2017, 01, 05]).fromNow(); // a day ago
should be 应该
moment([2017, 01, 05]).fromNow(); // 24 hours ago
I know it's possible to do this using .diff
and probably other similar functions and then adding the text, but is it possible to use .fromNow()
to do this? 我知道可以使用
.diff
和其他类似函数然后添加文本来执行此操作,但是可以使用.fromNow()
来执行此操作吗?
You can use relativeTimeThreshold
to customize thresholds for moment relative time. 您可以使用
relativeTimeThreshold
自定义时刻相对时间的阈值。
As the docs says: 正如文档所说:
duration.humanize
has thresholds which define when a unit is considered a minute, an hour and so on.duration.humanize
具有阈值,用于定义何时将单位视为分钟,一小时等。 For example, by default more than 45 seconds is considered a minute, more than 22 hours is considered a day and so on.例如,默认情况下,超过45秒被视为一分钟,超过22小时被视为一天,依此类推。 To change those cutoffs use
moment.relativeTimeThreshold(unit, limit)
where unit is one ofs
,m
,h
,d
,M
.要更改这些截止值,请使用
moment.relativeTimeThreshold(unit, limit)
,其中unit是s
,m
,h
,d
,M
。
In your case, you can increase hour thresholds to get relative days as hours. 在您的情况下,您可以增加小时阈值以将相对天数作为小时。 Here a working example showing time as hours from 1 hour to 26 days:
这是一个工作示例,显示从1小时到26天的小时数:
var m1 = moment().subtract(5, 'h'); var m2 = moment().subtract(55, 'h'); var m3 = moment().subtract(1, 'd'); // Default results console.log(m1.fromNow()); console.log(m2.fromNow()); console.log(m3.fromNow()); // Change relativeTimeThreshold moment.relativeTimeThreshold('m', 60); moment.relativeTimeThreshold('h', 24*26); // Results in hours console.log(m1.fromNow()); console.log(m2.fromNow()); console.log(m3.fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Note that, if you need, moment lets you customize relative time further with relativeTime
( here one of my examples) and relativeTimeRounding
method. 请注意,如果需要,moment允许您使用
relativeTime
( 这里是我的一个示例)和relativeTimeRounding
方法进一步自定义相对时间。
If you definitely want to use fromNow()
, I don't see any way other than overriding moment's built-in function. 如果你肯定想使用
fromNow()
,除了重写moment的内置函数之外我什么都看不到。 For example, you can override it to return the difference in hours as follows: 例如,您可以覆盖它以返回小时数差异,如下所示:
moment.fn.fromNow = function (a) {
var duration = moment().diff(this, 'hours');
return duration;
}
Then you can check that fromNow()
returns the value in hours: 然后你可以检查
fromNow()
以小时为单位返回值:
console.log(moment([2017,0,6]).fromNow());
which returns: 返回:
19
Note: Tried at 19:00 :) 注意:尝试在19:00 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.