Skip to content
Related Articles

Related Articles

Moment.js moment.duration().months() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 15 Jun, 2022
View Discussion
Improve Article
Save Article

The moment().duration().months() method is used to get the month of the duration. This method returns a value between 0 and 11.

This method is different from the asMonths() method which returns the length of the given duration in months.

Syntax:

moment().duration().months();

Parameters: This method does not accept any parameters.

Return Value: This method returns the months (0-11) of the duration.

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.duration().months() Method.

Example 1:

Javascript




const moment = require('moment');
  
// Example 1
let durationOne = moment.duration(9, 'months');
let durationTwo = moment.duration(19, 'months');
  
// This returns 9 as it would be the 9th month
// in the first year of the duration
console.log(
  "durationOne months is:", durationOne.months()
)
  
// This returns 7 as it would be the 7th month
// in the second year of the duration
console.log(
  "durationTwo months is:", durationTwo.months()
)


Output:

durationOne months is: 9
durationTwo months is: 7

Example 2: This example will help to understand the difference of this method with asMonths() for a better understanding.

Javascript




const moment = require('moment');
  
let durationA = moment.duration(50, 'weeks');
let durationB = moment.duration(64, 'weeks');
  
// The asMonths() method will return a value
// of the actual number of months of the duration
console.log(
  "Length of durationA in months is:",
  durationA.asMonths()
)
  
// The months() method will return the
// month of the duration
// It can be denoted as floor(numberOfMonths % 12)
console.log(
  "durationA months is:", durationA.months()
)
  
console.log(
  "Length of durationB in months is:",
  durationB.asMonths()
)
console.log(
  "durationB months is:", durationB.months()
)


Output:

Length of durationA in months is: 11.499209429351732
durationA months is: 11
Length of durationB in months is: 14.718988069570218
durationB months is: 2

Reference: https://momentjs.com/docs/#/durations/months/


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!