Open In App

Moment.js moment().date() Method

Last Updated : 18 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().date() method is used to get or set the day of the month of the Moment object. The range for setting the day can be between 1 and 31. When the range is exceeded, the day will extend to the previous or next months. This is also the same case in months that do not have all the 31 days, and hence will go to the next month when using a larger value.

Syntax:

moment().date( Number );

Parameters: This method accepts a single parameter as mentioned above and described below:

  • Number: It is the day of the month that has to be set for the Moment object. it is an optional parameter.

Return Value: This method returns the day of the month of the Moment.

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.

Moment.js can be installed using the following command:

Installation of moment module:

npm install moment

The below examples will demonstrate the Moment.js moment().date() Method.

Example 1:

Javascript




const moment = require('moment');
  
console.log("Current Date:", moment().toString())
console.log("Current date is:", moment().date())
  
let date10 = moment().date(10);
console.log(
    "Moment with date of 10 is:",
    date10.toString()
)
  
let date30 = moment().date(30);
console.log(
    "Moment with date of 30 is:",
    date30.toString(
))


Output:

Current Date: Mon Jul 18 2022 01:49:32 GMT+0530
Current date is: 18
Moment with date of 10 is: Sun Jul 10 2022 01:49:32 GMT+0530
Moment with date of 30 is: Sat Jul 30 2022 01:49:32 GMT+0530

Example 2:

Javascript




const moment = require('moment');
  
let momentX = moment().year(2019).month(6).date(5);
  
console.log("momentX Date:", momentX.toString())
console.log("momentX date is:", momentX.date())
  
let date45 = momentX.date(45);
console.log(
    "momentX with date of 45 is:"
    date45.toString()
)
  
let negativeDate45 = momentX.date(-45);
console.log(
    "momentX with date of -45 is:",
    negativeDate45.toString()
)


Output:

momentX Date: Fri Jul 05 2019 01:49:32 GMT+0530
momentX date is: 5
momentX with date of 45 is: Wed Aug 14 2019 01:49:32 GMT+0530
momentX with date of -45 is: Sun Jun 16 2019 01:49:32 GMT+0530

Reference: https://momentjs.com/docs/#/get-set/date/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads