【问题标题】:Strange behavior of new Date(), returns the next monthnew Date() 的奇怪行为,返回下个月
【发布时间】:2021-04-02 13:30:08
【问题描述】:

非常感谢您的帮助和解释。

我创建了一个方法,通过从两个参数(年份和月份)设置日期来返回一个月中的所有日期:

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
}

使用参数2021和0调用方法

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

我得到的不是一月份的天数,而是二月的天数!

这是我的 console.log console.log

【问题讨论】:

  • 因为您将相同的对象(而不是副本)推送到数组的每个元素并在每次循环迭代时修改该对象。每次迭代创建一个new Date
  • @charlietfl 谢谢!
  • days.push(new Date(year, month, date.getDate())) 可能会修复它

标签: javascript typescript date datetime


【解决方案1】:

new Date() 在每次推送项目时生成新的日期实例:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2021-01-31
    • 2019-01-24
    • 2013-12-11
    • 2012-12-01
    相关资源
    最近更新 更多