如何让 moment.js 以秒为单位显示相对时间? [英] How to make moment.js show relative time in seconds?
本文介绍了如何让 moment.js 以秒为单位显示相对时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下脚本显示了从现在到 2017/07/03 的相对时间.
The following script shows the relative time from now to 2017/07/03.
document.write(moment("20170703 00:00:00", "YYYYMMDD hh:mm:ss").fromNow());
<script src="https://cdn.bootcss.com/moment.js/2.17.1/moment.min.js"></script>
它返回类似 5 个月内
的东西,而我期望类似 在 123456789 秒内
.
It returns something like in 5 months
, while I expect something like in 123456789 seconds
.
推荐答案
您可以使用 diff
指定 'seconds'
单位作为第二个参数:
You can get seconds between two moment objects using diff
specifing 'seconds'
unit as second parameter:
var mom = moment("20170703 00:00:00", "YYYYMMDD HH:mm:ss");
document.writeln(mom.fromNow());
document.writeln(mom.diff(moment(), 's'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
如果您需要自定义时刻显示相对时间的方式(例如 fromNow()
输出),您可以使用 relativeTimeThreshold
和 relativeTime
.举个例子:
If you need to customize how moment shows relative time (e.g. the fromNow()
output) you can use relativeTimeThreshold
and relativeTime
. Here an example:
var mom = moment("20170703 00:00:00", "YYYYMMDD HH:mm:ss");
console.log(mom.fromNow());
// Change relativeTimeThreshold
moment.relativeTimeThreshold('s', 60*60*24*30*12);
moment.updateLocale('en', {
relativeTime : {
s: function (number, withoutSuffix, key, isFuture){
return number + ' seconds';
},
}
});
console.log(mom.fromNow());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
这篇关于如何让 moment.js 以秒为单位显示相对时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文