Moment.js moment.duration().years() Method
The moment().duration().years() method is used to get the years of the duration. This method returns the number of complete years in the duration, thereby returning a whole number as the value.
This method is different from the asYears() method which returns the length of the given duration in years as it can have decimals to denote an incomplete year.
Parameters: This method does not accept any parameters.
Return Value: This method returns the years 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().years() Method.
durationOne years is: 0 durationTwo years is: 1
Example 2: This example will help to understand the difference of this method with asYears() for a better understanding.
Length of durationA in years is: 1.2457476881797709 durationA years is: 1 Length of durationB in years is: 4.906329356523406 durationB years is: 4