Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting year in moment.js

Tags:

momentjs

What is the differenct between those two:

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

Is it just type of or anything else? I am just curious.

like image 307
Marek Avatar asked Aug 04 '14 09:08

Marek


People also ask

How do you find the year in a moment?

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.

How do you find the month and year in a moment?

var check = moment('date/utc format'); day = check. format('dddd') // => ('Monday' , 'Tuesday' ----) month = check. format('MMMM') // => ('January','February.....) year = check.

How can I get last year's moment?

let today = moment(); let lastYear = moment(). subtract(1, 'year') .

How do you add 1 month in moment?

Try moment('2020-03-30'). add(1, 'months') and then compare with moment('2020-03-31'). add(1, 'months') .


2 Answers

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.

like image 186
Matt Johnson-Pint Avatar answered Sep 18 '22 18:09

Matt Johnson-Pint


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>
like image 22
Saurabh Mistry Avatar answered Sep 20 '22 18:09

Saurabh Mistry