0

I am trying to get the month of the given date as a string in javaScript but I get the wrong month of the date displayed.

var d = new Date("Sun Dec 13 2020 08:00:00 GMT+0530");
console.log(d.getMonth());

I get in the console output for month as 11 for some reason.

3 Answers3

2

Solution

The range begins at zero and not at one

So refering the mdn docs

monthIndex Integer value representing the month, beginning with 0 for January to 11 for December.

The range from getMonth() is 0-11

So the solution is just to add +1 to the result of the getMonth() method

console.log(d.getMonth() +1 );
Aalexander
  • 4,987
  • 3
  • 11
  • 34
1

the count starts from 0 -january, 1-feb,...11-december

Abhishek
  • 89
  • 7
-1

just call this and it is done.

function month(){
 const today = new Date();
 const options = {
    month: "long"
  };

  return today.toLocaleDateString("en-US", options);
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Yash Garg
  • 1
  • 2