-2

The Date.getMonth() returns different values for same date in different formats.

The first statement is in the UTC format.

The second one uses YYYY,M,DD format.

I didn't expect it to return a different value because it's the same date. What is going on?

console.log(new Date('July 20, 69 00:20:18').getMonth()); // returns 6
console.log(new Date(1969, 7, 20).getMonth()); // returns 7
zelite
  • 1,478
  • 16
  • 37
anoop chandran
  • 1,460
  • 5
  • 23
  • 42

4 Answers4

1

For your first example - read MDN docs for Date.getMonth(). It returns a zero-indexed numerical month representation where January is represented by 0, and December by 11. Thus, July is represented (correctly) by 6.

The second one doesn't use a format per se, it's passing the values as parameters to the Date constructor. The MDN docs for Date() state that the parameter you're passing with a value 7 is also a monthIndex. Thus, to correctly notate July, pass 6 instead.

esqew
  • 42,425
  • 27
  • 92
  • 132
1

The getMonth method returns a zero based value. Meaning 0 indicates the first month. Creating a new Date object like in your second example follows the same principle.

See these examples.

Kevin
  • 401
  • 2
  • 9
0

The months in a Date object are zero indexed. That means they range from 0 to 11.

new Date('July 20, 69 00:20:18') creates a Date with the month of July which has the index 6.

new Date(1980, 7, 20) creates a date with the month with the 7th index, which is August.

Here you can find more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

zelite
  • 1,478
  • 16
  • 37
0

That diference happens because when using integer parameters to new Date(1980, 6, 20) the month parameter starts in 0, not 1. example:
0 - january
1 - february
...
5 - july
6 - august
...
11 - december

So your result is

var dateString = new Date('July 20, 69 00:20:18') // "1969-07-20T03:20:18.000Z"
var dateInt = new Date(1980, 7, 20) // "1980-08-20T03:00:00.000Z"

console.log(dateString.getMonth()); // 6
console.log(dateInt.getMonth()); // 7