I'm using Moment.js included through RequireJS. When I call Moment().month()
, instead of number 11 I always get number 10. Any ideas how can this happen?
Getting wrong month in moment.js
Asked Answered
According to Moment.js documentation, 'month' uses an array and the indices of an array are zero-based. Therefore, January is set to '0' and December is set to '11'.
For example, moment().month('November');
prints '10'.
Just a clarification. 0-based indexing of the months is a feature that Moment.js inherits from Javascript. See the ECMAScript specification at par.15.9.1.4 for further details. –
Trilby
Almost feels like they should expose it as 1-12 for the sake of intuitive use in lieu of the the ECMAScript specification. –
Cartogram
by this logic why arent year, date, hours and minutes zero based?(snark, sorry) –
Bloodred
They actually claim month is not zero based: M MM 1..12 Month number –
Furman
working link to ECMAScript month spec: ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 –
Computerize
We should create a dedicated web page that states the total dev time wasted by this. –
Lindsay
moment().month gets or sets the month and accepts numbers from 0 to 11. Key here is that index starts at 0, not 1. The below code will work as a solution for this question.
{Moment(yourDate).month(Moment(yourDate).month()-1).format("MMMM Do YYYY")}
The above code for 8/30/2022 will show August 30th 2022.
{Moment(yourDate).month(Moment(yourDate).month()-1).format("MM-DD-YYYY")}
The above code for 8/30/2022 will show 08-30-2022.
{Moment(yourDate).format("MM-DD-YYYY")}
The above code for 8/30/2022 will show 09-30-2022.
© 2022 - 2024 — McMap. All rights reserved.
Note: Months are zero indexed, so January is month 0.
– Promontorymoment.parseZone('12/01/2018','MM/DD/YYYY').add({M:1}).month()
– Philpot