What is difference between 'year()' and 'format('YYYY')'?

JavascriptMomentjs

Javascript Problem Overview


What is the difference between those two:

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

Is it just type of a returned value or anything else?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarekView Question on Stackoverflow
Solution 1 - JavascriptMatt Johnson-PintView Answer on Stackoverflow
Solution 2 - JavascriptSaurabh MistryView Answer on Stackoverflow