Moment.js Customize Calendar Format
In this article, we will discuss the moment.js Customize Calendar Format in detail with examples. Moment.js is very easy to customize. In general, you should create a locale setting with your customizations.
The moment().calendar() function is used to display calendar time which is relative to a given referenceDay. By default, it is set to the start of the current day i.e. today.
Syntax:
moment().calendar(referenceDay, formats);
Parameters: This function has two parameters, the first one is the referenceDay and another one is the format.
Return Value: This function returns the date.
Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory. For more details, please refer to this link.
Installation of moment module: Moment.js can be installed using the following command.
npm install moment
Example 1: In this example, we call the function twice as in the first call we are passing the date() as the parameter to the moment.calendar function to get the current date and time and further in the second call we are simply calling the function as it is and comparing the results accordingly.
index.js
Javascript
// 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); |
Step to run the application: Run the index.js file using the below command.
node index.js
Output:
Result using new Date() function with moment.calendar:- Event Will Happen Today Result using new Date() function without moment.calendar:- Event Already Happened Today
Example 2: In this example, we are simply calling the moment.calendar() function to get the result as the current time along with today as the output by passing the date as the moment as the function’s parameter in the JavaScript programming language.
index.js
Javascript
// 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); |
Step to run the application: Run the index.js file using the below command.
node index.js
Output:
Result: Today at 10:02 AM
Reference: https://momentjs.com/docs/#/displaying/calendar-time/
Contact Us