gpt4 book ai didi

javascript - JS 日期无法获得 31 天的月份的最后一天

转载 作者:行者123 更新时间:2023-12-04 07:52:28 25 4
gpt4 key购买 nike

这个月(三月)有 31 天。
我想得到这个月的最后一天而不是得到 2021 年 3 月 31 日星期三 23:59:59 我收到 2021 年 4 月 30 日星期五 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)
请注意,在第二个示例中 - 运行良好,我们得到了二月的最后一天和 GMT+2 (IST) 而不是 GMT+3 (IDT)
还要注意,如果我这样声明: let d = new Date('2021-03-25')它也很好用(具有特定日期,而不仅仅是 new Date() )

最佳答案

这是因为四月只有 30 天。

let d = new Date()

d.setMonth( d.getMonth() + 1) // Actually April 31st -> May 1st.

关于javascript - JS 日期无法获得 31 天的月份的最后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66886058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com