Open In App

Moment.js moment().year() Method

The moment().year() method is used to get or set the year of the Moment object. The year value that can be set has a range from -270,000 to 270,000.

Syntax:



moment().year( Number );

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

Return Value: This method returns the current year 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().year() Method.

Example 1:




const moment = require('moment');
  
console.log("Current Date:", moment().toString())
console.log("Current year is:", moment().year())
  
let year2050 = moment().year(2050);
console.log("Year of 2050 is:", year2050.toString())
  
let year1950 = moment().year(1950);
console.log("Year of 1950 is:", year1950.toString())

Output:

Current Date: Mon Jul 11 2022 02:09:59 GMT+0530
Current year is: 2022
Year of 2050 is: Mon Jul 11 2050 02:09:59 GMT+0530
Year of 1950 is: Tue Jul 11 1950 02:09:59 GMT+0530

Example 2:




const moment = require('moment');
  
console.log("Current Date:", moment().toString())
console.log("Current year is:", moment().year())
  
let negativeYear50 = moment().year(-50);
console.log(
    "Negative Year of 50 is:",
    negativeYear50.toString()
)
  
let negativeYear1000 = moment().year(-1000);
console.log(
    "Negative Year of 1000 is:",
    negativeYear1000.toString()
)

Output:

Current Date: Mon Jul 11 2022 02:09:59 GMT+0530
Current year is: 2022
Negative Year of 50 is: Tue Jul 11 -0050 02:09:59 GMT+0553
Negative Year of 1000 is: Fri Jul 11 -1000 02:09:59 GMT+0553

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


Article Tags :