Open In App

Moment.js moment().year() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Number: It is the year that has to be set for the Moment object. it is an optional parameter.

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:

Javascript




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:

Javascript




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/



Last Updated : 12 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads