Moment.js moment.duration().months() Method
Last Updated :
15 Jun, 2022
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' );
let durationOne = moment.duration(9, 'months' );
let durationTwo = moment.duration(19, 'months' );
console.log(
"durationOne months is:" , durationOne.months()
)
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' );
console.log(
"Length of durationA in months is:" ,
durationA.asMonths()
)
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/
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...