Moment.js 自定义序数名称
Moment.js 是一个用于解析、验证、操作和格式化日期的JavaScript日期库。Moment输出的日期数值的序数可以根据我们的需求进行自定义。我们将使用 moment.updateLocale() 方法 来实现此功能。
语法:
moment.updateLocale('en', {
ordinal: callback_function
});
参数: updateLocale 方法接受一个具有 ordinal 属性的对象,该属性可用于指定用于自定义序数名称的回调函数。
数字的默认序数如下:
- 1:st
- 2:nd
- 3:rd
- 4:th
- 5:th
- 6:th
- 7:th
- 8:th
- 9:th
注意: 在普通的 Node.js 程序中,这无法工作,因为它需要安装 moment.js 库。
可以使用以下命令安装 Moment.js:
npm install moment
示例1:
// Acquiring the plugin
var moment = require("moment");
// Customizing the ordinal method
var ordinal_name = moment.updateLocale("en", {
ordinal: function (num) {
var last_digit = num % 10;
var ordinal = ~~((num % 100) / 10) === 1
? "`th"
: last_digit === 1
? "`st"
: last_digit === 2
? "`nd"
: last_digit === 3
? "`rd"
: "`th";
return num + ordinal;
},
});
console.log("Ordinal name of 3 is:", ordinal_name.ordinal(3));
console.log("Todays Date is:", moment().format('Do'))
输出:
Ordinal name of 3 is: 3`rd
Todays Date is: 13`th
示例2:
// Acquiring the plugin
var moment = require("moment");
// Customizing the ordinal method
var ordinal_name = moment.updateLocale("en", {
ordinal: function (num) {
var last_digit = num % 10;
var ordinal = ~~((num % 100) / 10) === 1
? "-TH"
: last_digit === 1
? "-ST"
: last_digit === 2
? "-ND"
: last_digit === 3
? "-RD"
: "-TH";
return num + ordinal;
},
});
console.log("Ordinal name of 5 is:", ordinal_name.ordinal(5));
console.log("Todays Date is:", moment().format('Do'))
输出:
Ordinal name of 5 is: 5-TH
Todays Date is: 13-TH
参考: https://momentjs.com/docs/#/customization/ordinal/