Moment.js 自定义相对时间阈值
本文将详细介绍Moment.js自定义相对时间阈值,并提供示例。Moment.js非常容易自定义。一般来说,您应该创建一个使用您自定义设置的地区设置。
moment.relativeTimeThreshold() 用于duration。使用这个方法,可以将持续时间以几秒、几分钟、几小时等方式显示。几秒前的持续时间预先确定并显示;分钟和小时也是如此。通过使用相对时间阈值方法,您可以修改以秒、分钟、小时和天为单位的限制。
语法:
moment.relativeTimeThreshold(unit); // getter
moment.relativeTimeThreshold(unit, limit); // setter
要更改这些截止时间,使用moment.relativeTimeThreshold(unit,limit),其中limit是s,m,h,d,M之一:
- ss - 数秒的最少数目,用于计算秒数,减1。必须在设置
s
单位之后设置,或者在不设置s
单位的情况下设置。 - s - 少于这个数的秒将被视为一分钟。
- m - 少于这个数的分钟将被视为一小时。
- h - 少于这个数的小时将被视为一天。
- d - 少于这个数的天将被视为一个月。
- w - 少于这个数的周将被视为一个月。默认情况下不使用。
- M - 少于这个数的月将被视为一年。
注意: 这在普通的Node.js程序中不起作用,因为它需要全局安装或在项目目录中安装一个外部的moment.js库。更多详情,请参考此链接。
可以使用以下命令安装moment.js:
moment模块的安装:
npm install moment
示例1: 在本示例中,我们将通过相应地传递参数到JavaScript编程语言中的 moment.relativeTimeThreshold() 函数来查看默认时间,以几秒、秒、分钟、小时、天和月为单位。
// Importing moment module
const moment = require('moment');
const a = moment.relativeTimeThreshold('ss');
console.log("
Least number of seconds to be counted in seconds", a);
const b = moment.relativeTimeThreshold('s');
console.log("
Least number of seconds to be considered as a minute", b);
const c = moment.relativeTimeThreshold('m');
console.log("
Least number of minutes to be considered as a hour", c);
const d = moment.relativeTimeThreshold('h');
console.log("
Least number of hours to be considered as a day", d);
const e = moment.relativeTimeThreshold('d');
console.log("
Least number of days to be considered as a month", e);
const f = moment.relativeTimeThreshold('M');
console.log("
Least number of seconds to be considered as a minute", f);
输出:
Least number of seconds to be counted in seconds 44
Least number of seconds to be considered as a minute 45
Least number of minutes to be considered as a hour 45
Least number of hours to be considered as a day 22
Least number of days to be considered as a month 26
Least number of seconds to be considered as a minute 11
注意: 分钟阈值从默认的45变为5,对于6分钟的人性化输出显示为一个小时。
示例2: 在这个示例中,我们将把分钟阈值从默认的45改为15,利用moment.relativeTimeThreshold()和moment.duration().humanize()函数将6分钟的人性化输出显示为6分钟,并在javascript中显示设置的分钟的人性化输出。
// Importing moment module
const moment = require('moment');
moment.relativeTimeThreshold('m', 5);
const c = moment.duration(8, "minutes").humanize(true);
console.log(c)
moment.relativeTimeThreshold('m', 15);
c = moment.duration(8, "minutes").humanize(true);
console.log(c)
输出:
in an hour
in 8 minutes
参考: https://momentjs.com/docs/#/customization/relative-time-threshold/