Getting year in moment.js

Solution 1:

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

Solution 2:

var year1 = moment().format('YYYY');
var year2 = moment().year();

console.log('using format("YYYY") : ',year1);
console.log('using year(): ',year2);

// using javascript 

var year3 = new Date().getFullYear();
console.log('using javascript :',year3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>