Moment.js moment.duration().locale() 方法
moment().duration().locale() 方法用于返回或设置持续时间的区域设置。持续时间的区域设置还将影响到一些返回文本时间的方法,例如 humanize() 方法,不同的区域设置将影响到文本的语言。
语法:
moment().duration().locale(String)
参数:
这个方法接受一个参数,如上所述,具体描述如下:
- String: 这是一个指定要应用的本地化设置的字符串。
返回值:
它返回持续时间的当前区域设置。
注意:
这个方法在普通的Node.js程序中不起作用,因为它需要全局安装或项目目录中安装一个外部的moment.js库。
Moment.js可以通过以下命令进行安装:
moment模块的安装:
npm install moment
以下示例将演示Moment.js的 moment.duration().locale() 方法。
示例1:
const moment = require('moment');
// Get current locale
let durationOne = moment.duration(9, 'months');
console.log(
"The locale of durationOne is:",
durationOne.locale()
);
console.log(
"The humanized version of durationOne is:",
durationOne.humanize()
);
// Set locale to 'es'
let durationTwo =
moment.duration(9, 'months').locale('es');
console.log(
"The humanized version of durationTwo is:",
durationTwo.humanize()
);
// Set locale to 'it'
let durationThree =
moment.duration(9, 'months').locale('it');
console.log(
"The humanized version of durationThree is:",
durationThree.humanize()
);
输出:
The locale of durationOne is: en
The humanized version of durationOne is: 9 months
The humanized version of durationTwo is: 9 meses
The humanized version of durationThree is: 9 mesi
示例2:
const moment = require('moment');
// Get current locale
let durationA = moment.duration(9, 'months');
console.log(
"The humanized version of durationA is:",
durationA.humanize()
);
// Set locale to 'es'
let durationB = moment.duration(9, 'months').locale('es');
console.log(
"The humanized version of durationB is:",
durationB.humanize()
);
// Set locale to 'it'
let durationC = moment.duration(9, 'months').locale('it');
console.log(
"The humanized version of durationC is:",
durationC.humanize()
);
输出:
The humanized version of durationA is: 9 months
The humanized version of durationB is: 9 meses
The humanized version of durationC is: 9 mesi
参考: https://momentjs.com/docs/#/durations/locale/