Як Цидрак
Як Цидрак

Reputation: 41

Strange behavior of new Date(), returns the next month

I would really appreciate your help and explanation.

I made a method that returns all the days of the month, by setting the date from two parameters-the year and the month:

private _getDaysOfMonth(year: number, month: number): Array<Date> {
    const date = new Date(year, month, 1)

    const days = []
    while (date.getMonth() === month) {
        days.push(date) 
        console.log(date) // works correctly, example: Fri Jan 01 2021 00:00:00 GMT+0300 (Moscow Standard Time)
        date.setDate( date.getDate() + 1 )
    }
   
    console.log(days) // I expect an array of days from January 1 to January 31, 2021, But I get February
    return days
}

Calling the method with the parameters 2021 and 0

this._getDaysOfMonth(this._year, this._month)

And instead of an array of days in January, I get an array of days in February!

This is my console.log console.log

Upvotes: 2

Views: 44

Answers (1)

Waelsy123
Waelsy123

Reputation: 612

new Date() to generate new date instance every time you push an item:

function getDaysOfMonth (year, month) {
  const date = new Date(year, month)

  const days = []
  while (date.getMonth() === month) {
    days.push(new Date(date)) // new Date() to generate new date instance
    console.log(date)
    date.setDate(date.getDate() + 1)
  }

  console.log(days)
  return days
}

getDaysOfMonth(2021, 1)

Upvotes: 1

Related Questions