javascript - date.toLocaleString 有错误吗?

标签 javascript date

我正在构建一个日历应用程序,当滚动月份时,我注意到三月出现了两次。在验证我正确地度过了几个月后,我去检查了 date.toLocaleString 函数,并发现了一些问题。在我的浏览器控制台中,出现了这个问题。
image of date bug

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/

相关文章:

javascript - axios.delete 正在从 firebase 数据库中删除所有节点

javascript - 从不同的js文件访问变量

ruby-on-rails - ruby rails : SQLite3 to PostgreSQL null date

java - 具有设置字段的日期每次调用时都会给出任意值

objective-c - ALAssetPropertyDate 返回 "wrong"日期

javascript - WebAssembly.instantiate 既没有调用,也没有在 v8 嵌入中捕获

javascript - 突出显示构建谷歌地图 v3

javascript - HTML5 气泡消息

java - 如何在 Java 中将这个 "Tue Nov 13 14:35:04 +0000 2012"String 格式转换为日期?

用c计算圣诞节前的时间