我的片刻持续时间为 14 秒。
const duration = moment.duration(end.diff(startTime));
如果我想将此持续时间显示为格式化字符串,我可以使用 .humanize()
duration.humanize(true)
// in a few seconds
这很好用,但是有没有一种方法可以暂时将其格式化为精确持续时间,例如 14 秒
或更长的持续时间,在 2 天 5 小时内
而不是 在 2 天内
?
最佳答案
您可以自定义相对时间函数的输出,例如 humanize()
使用 relativeTime
updateLocale
和 relativeTimeThreshold
的键.
我不知道一般持续时间的预期输出是什么,但您可以使用以下代码在 14 秒内
获得 14 秒的持续时间:
const startTime = moment();
const end = moment().add(14, 'seconds');
const duration = moment.duration(end.diff(startTime));
console.log( duration.humanize(true) );
moment.relativeTimeThreshold('ss', 60);
moment.updateLocale('en', {
relativeTime : {
s: function (number, withoutSuffix, key, isFuture){
return number + ' seconds';
}
}
});
console.log( moment.duration(end.diff(startTime)).humanize(true) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
关于javascript - Moment JS持续时间人性化更精确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53828729/