Getting wrong month in moment.js
Asked Answered
R

2

37

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?

Raper answered 20/11, 2013 at 11:33 Comment(6)
Isn't january month 0? Note: Months are zero indexed, so January is month 0.Promontory
in javascript's Date, months are counted 0-11. w3schools.com/jsref/jsref_obj_date.aspEartha
Try Moment().format("MM")Mesopause
You can always use the .add method to account for the zero index .add(1, 'M')Barefaced
@JeremyHamm That doesn't work for December. moment.parseZone('12/01/2018','MM/DD/YYYY').add({M:1}).month()Philpot
Thank you @RenatoGama : it returns the correct month number, starting from one.Samba
H
78

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'.

Halie answered 20/11, 2013 at 11:41 Comment(6)
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 numberFurman
working link to ECMAScript month spec: ecma-international.org/ecma-262/5.1/#sec-15.9.1.4Computerize
We should create a dedicated web page that states the total dev time wasted by this.Lindsay
V
1

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.

Varve answered 5/10, 2022 at 5:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.