javascript Moment.js unix 时间戳以始终以分钟为单位显示时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12134568/
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
Moment.js unix timestamp to display time ago always in minutes
提问by Scott Bartell
I am using Moment.js and would like to convert unix timestamps to (always) display minutes ago from the current time. E.g.) 4 mins ago, 30 mins ago, 94 mins ago, ect.
我正在使用 Moment.js 并希望将 unix 时间戳转换为(总是)显示从当前时间开始的几分钟前。例如)4 分钟前、30 分钟前、94 分钟前等。
Right now I am using:
现在我正在使用:
moment.unix(d).fromNow()
But this does not always display in minutes e.g.) an hour ago, a day ago, ect. I have tried using .asMinutes() but I believe this only words with moment.duration().
但这并不总是以分钟为单位显示,例如)一小时前、一天前等。我曾尝试使用 .asMinutes() 但我相信这只是带有 moment.duration() 的词。
采纳答案by Fabrício Matté
Not sure if this is possible with native Moment methods, but you can easily make your own Moment extension:
不确定原生 Moment 方法是否可行,但您可以轻松制作自己的 Moment 扩展:
moment.fn.minutesFromNow = function() {
return Math.floor((+new Date() - (+this))/60000) + ' mins ago';
}
//then call:
moment.unix(d).minutesFromNow();
Note that other moment methods won't be chainable after minutesFromNow()
as my extension returns a string.
请注意,在minutesFromNow()
我的扩展返回一个字符串后,其他矩方法将无法链接。
edit:
编辑:
Extension with fixed plural (0 mins, 1 min, 2 mins):
固定复数扩展(0 min s, 1 min, 2 min s):
moment.fn.minutesFromNow = function() {
var r = Math.floor((+new Date() - (+this))/60000);
return r + ' min' + ((r===1) ? '' : 's') + ' ago';
}
You can as well replace "min" with "minute" if you prefer the long form.
如果您更喜欢长格式,也可以将“min”替换为“minute”。
回答by Greg Ross
Just modify the "find" function in the moment.js code, so that it returns minutes:
只需修改 moment.js 代码中的“查找”函数,使其返回分钟:
from : function (time, withoutSuffix) {
return moment.duration(this.diff(time)).asMinutes();
}
Here's an example.
这是一个例子。
...or, even better. Just add this as a new function called "fromNowInMinutes".
……或者,甚至更好。只需将其添加为名为“fromNowInMinutes”的新函数即可。