简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM