Open In App

Moment.js moment().calendar() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The moment().calendar() function is used to displays 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.

Installation of moment module:

  1. You can visit the link to Install moment module. You can install this package by using this command.
    npm install moment
  2. After installing the moment module, you can check your moment version in the command prompt using the command.
  3. npm version moment
  4. After that, you can just create a folder and add a file for example, index.js as shown below.

Example 1: Filename: index.js 
 

javascript




// Requiring the module
const moment = require('moment');
   
// Function call
var result1 = moment(new Date()).calendar(null, {
    sameDay: function (now) {
      if (this.isBefore(now)) {
        return '[Something Will Happen Today Only]';
      } else {
        return '[Something Already Happened Today]';
      }
    }
});
  
var result2 = moment().calendar(null, {
    sameDay: function (now) {
       if (this.isBefore(now)) {
          return '[Something Will Happen Today Only]';
       } else {
          return '[Something Already Happened Today]';
       }
    }
});
  
console.log(result1);
console.log(result2);


Steps to run the program:

  1. The project structure will look like this:
  2. Run index.js file using below command:
    node index.js

Output:

Something Will Happen Today Only
Something Already Happened Today

Example 2: Filename: index.js

javascript




// Requiring the module
const moment = require('moment');
   
function getCalendar(date){
   return moment().calendar();
}
   
// Function call
var result = getCalendar(moment);
console.log("Result:", result);


Steps to run the program: 
 

  1. The project structure will look like this:
  2. Run index.js file using below command:
    node index.js
  3. Output:

    Result: Today at 10:28 PM

    Reference: https://momentjs.com/docs/#/displaying/calendar-time/
     



    Last Updated : 21 Jul, 2021
    Like Article
    Save Article
    Previous
    Next
    Share your thoughts in the comments
Similar Reads