本月(3 月)有 31 天。 我想获取该月的最后一天,而不是获取 Wed Mar 31 2021 23:59:59 我得到 Fri Apr 30 2021 23:59:59 看:
let d = new Date()
d.setMonth( d.getMonth() + 1) // April
d.setDate(0) // should bring the 31 of March
d.setHours(23, 59, 59, 999)
console.log(d) // Fri Apr 30 2021 23:59:59 GMT+0300 (IDT)
为什么会发生在31天的日期?
当每个月的不同月份进行尝试时,它也有效,例如:
let d = new Date("2021-02-25") // notice that we point to February
d.setMonth( d.getMonth() + 1)
d.setDate(0)
d.setHours(23, 59, 59, 999)
console.log(d) // Sun Feb 28 2021 23:59:59 GMT+0200 (IST)
请注意,在第二个示例中,效果很好,我们得到了 2 月的最后一天和 GMT+2 (IST),而不是 GMT+3 (IDT)
另请注意,如果我这样声明: let d = new Date('2021-03-25')
它也可以很好地工作(使用特定日期,而不仅仅是 new日期()
)
最佳答案
发生这种情况是因为 4 月只有 30 天。
let d = new Date()
d.setMonth( d.getMonth() + 1) // Actually April 31st -> May 1st.
关于javascript - JS Date 无法获取31天的月份的最后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66886058/