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.
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.
var check = moment('date/utc format'); day = check. format('dddd') // => ('Monday' , 'Tuesday' ----) month = check. format('MMMM') // => ('January','February.....) year = check.
let today = moment(); let lastYear = moment(). subtract(1, 'year') .
Try moment('2020-03-30'). add(1, 'months') and then compare with moment('2020-03-31'). add(1, 'months') .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With