Moment.js 自定义日历格式
在本文中,我们将通过示例详细讨论moment.js自定义日历格式。moment.js非常容易进行自定义。通常,您应该创建一个具有自定义设置的区域设置。
moment().calendar() 函数用于显示相对于给定referenceDay的日历时间。默认情况下,它设置为当前天的开始,即今天。
语法:
moment().calendar(referenceDay, formats);
参数: 该函数有两个参数,第一个是referenceDay,另一个是format。
返回值: 该函数返回日期。
注意: 这在普通的Node.js程序中不起作用,因为它需要安装全局或项目目录中的外部moment.js库。有关更多细节,请参阅此 链接 。
安装moment module: 可以使用以下命令安装Moment.js。
npm install moment
示例1: 在这个示例中,我们调用函数两次。在第一次调用中,我们将date()作为参数传递给moment.calendar函数以获取当前的日期和时间。在第二次调用中,我们简单地调用函数,并根据结果进行比较。
index.js
// Importing moment module
const moment = require('moment');
// Function call
let Result = moment(new Date()).calendar(null, {
sameDay: function (now) {
if (this.isBefore(now)) {
return '[Event Will Happen Today]';
} else {
return '[Event Already Happened Today]';
}
}
});
let Result1 = moment().calendar(null, {
sameDay: function (now) {
if (this.isBefore(now)) {
return '[Event Will Happen Today]';
} else {
return '[Event Already Happened Today]';
}
}
});
console.log("Result using new Date()
function with moment.calendar:-", Result);
console.log("Result using new Date()
function without moment.calendar:-", Result1);
运行应用程序的步骤: 使用以下命令运行 index.js 文件。
node index.js
输出:
Result using new Date() function with moment.calendar:- Event Will Happen Today
Result using new Date() function without moment.calendar:- Event Already Happened Today
示例2: 在这个示例中,我们只是调用 moment.calendar() 函数,通过将日期作为参数传递给函数,在JavaScript编程语言中获得当前时间以及今天作为输出的结果。
index.js
// Importing moment module
const moment = require('moment');
// Function call
function getCalendar(date) {
return moment().calendar();
}
// Function call
let result = getCalendar(moment);
console.log("Result:", result);
运行应用程序的步骤: 使用以下命令运行index.js文件。
node index.js
输出:
Result: Today at 10:02 AM
参考: https://momentjs.com/docs/#/displaying/calendar-time/