Open In App

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

Last Updated : 15 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Syntax:

moment().duration().years();

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.

Example 1:

Javascript




const moment = require('moment');
  
let durationOne = moment.duration(250, 'days');
let durationTwo = moment.duration(500, 'days');
  
// This returns 0 as the duration would
// not even be a complete year
console.log(
  "durationOne years is:", durationOne.years()
)
  
// This returns 1 as the duration would be
// more than 1 year, but less than 2 years
console.log(
  "durationTwo years is:", durationTwo.years()
)


Output:

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.

Javascript




const moment = require('moment');
  
let durationA = moment.duration(65, 'weeks');
let durationB = moment.duration(256, 'weeks');
  
// The asYears() method will return a value
// of the actual number of years of the duration
console.log(
  "Length of durationA in years is:",
  durationA.asYears()
)
  
// The years() method will return the year
// of the duration
console.log("durationA years is:", durationA.years()
)
  
console.log(
  "Length of durationB in years is:", durationB.asYears()
)
console.log("durationB years is:", durationB.years())


Output:

Length of durationA in years is: 1.2457476881797709
durationA years is: 1
Length of durationB in years is: 4.906329356523406
durationB years is: 4

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads