我正在构建一个日历应用程序,当滚动月份时,我注意到三月出现了两次。在验证我正确地度过了几个月后,我去检查了 date.toLocaleString 函数,并发现了一些问题。在我的浏览器控制台中,出现了这个问题。
date.toLocaleString
是否存在错误,我该如何解决该问题?
最佳答案
今天是 2022 年 8 月 30 日。将月份设置为 2 月会将日期设置为 2022 年 2 月 30 日,即今年 2 月底过去了 2 天,实际上将日期设置为 2022 年 3 月 2 日。现在再次将月份设置为三月不会做任何事情,因为这个月已经是三月了。您可以通过在每个步骤后检查完整日期来验证这一点:
> date = new Date()
2022-08-30T02:57:10.017Z
> date.setMonth(1); date
2022-03-02T02:57:10.017Z
> date.setMonth(2); date
2022-03-02T02:57:10.017Z
> date.setMonth(3); date
2022-04-02T02:57:10.017Z
来自docs :
The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.
关于javascript - date.toLocaleString 有错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73536632/