35

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?

Ladislav M
  • 2,157
  • 4
  • 36
  • 52

2 Answers2

76

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

Graham John
  • 170
  • 12
Gnagy
  • 1,432
  • 16
  • 26
  • 16
    Just a clarification. 0-based indexing of the months is a feature that Moment.js inherits from Javascript. See the [ECMAScript specification](http://www.ecma-international.org/ecma-262/5.1/Ecma-262.pdf) at par.15.9.1.4 for further details. – Alberto De Caro Nov 20 '13 at 13:40
  • 13
    Almost feels like they should expose it as 1-12 for the sake of intuitive use in lieu of the the ECMAScript specification. – Naruto Sempai Sep 26 '15 at 15:22
  • 32
    by this logic why arent year, date, hours and minutes zero based?(snark, sorry) – Manuel Hernandez Apr 25 '16 at 05:17
  • 2
    They actually claim month is not zero based: M MM 1..12 Month number – Andriy Kharchuk Jun 03 '19 at 04:17
  • working link to ECMAScript month spec: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 – haja Jan 28 '20 at 15:07
  • 21
    We should create a dedicated web page that states the total dev time wasted by this. – Yaron Levi May 29 '20 at 16:40
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.

JavaGeek
  • 475
  • 5
  • 14