Moment.js moment().toObject() 方法
moment().toObject() 方法 用于将 Moment 对象以 Date 参数的属性形式转换为 JavaScript 对象。
语法:
moment().toObject();
参数: 此方法不接受任何参数:
返回值: 此方法将返回作为JavaScript对象的持续时间。
注意: 这在普通的Node.js程序中无法工作,因为它需要全局安装或在项目目录中安装外部的moment.js库。
可以使用以下命令安装Moment.js:
安装moment模块:
npm install moment
以下示例将演示 Moment.js moment().toObject() 方法 。
示例1:
const moment = require('moment');
let momentOne = moment();
let momentTwo = moment()
.add(15, 'months')
.add(10, 'days')
.add(24, 'seconds');
console.log(
"Object form of momentOne is:",
momentOne.toObject()
)
console.log(
"Object form of momentTwo is:",
momentTwo.toObject()
)
输出:
Object form of momentOne is: {
years: 2022,
months: 6,
date: 10,
hours: 23,
minutes: 36,
seconds: 3,
milliseconds: 659
}
Object form of momentTwo is: {
years: 2023,
months: 9,
date: 20,
hours: 23,
minutes: 36,
seconds: 27,
milliseconds: 659
}
示例2:
const moment = require('moment');
let momentA = moment(
'25/12/2022', 'DD/MM/YYYY'
);
let momentB = moment({
year: 2017, month: 5, day: 4,
hour: 1, minute: 15, second: 30,
millisecond: 100
});
console.log(
"Object form of momentA is:",
momentA.toObject()
)
console.log(
"Object form of momentB is:",
momentB.toObject()
)
输出:
Object form of momentA is: {
years: 2022,
months: 11,
date: 25,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
}
Object form of momentB is: {
years: 2017,
months: 5,
date: 4,
hours: 1,
minutes: 15,
seconds: 30,
milliseconds: 100
}
参考资料: https://momentjs.com/docs/#/displaying/as-object/