Home > Mobile >  Does date.toLocaleString have a bug?
Does date.toLocaleString have a bug?

Time:09-07

I'm building a calendar app, and when scrolling through months, I noticed March came up twice. After verifying I was going through the months correctly, I went and checked the date.toLocaleString function, and noticed something wrong. In my browser console, this came up.
image of date bug

Does date.toLocaleString have a bug, and how can I work around it?

CodePudding user response:

Today is 30th August 2022. Setting the month to February will set the date to 30th February 2022, which is 2 days past the end of February this year and actually sets the date to 2nd March 2022. Setting the month again now to March will not do anything as the month is already March. You can verify this by inspecting the full date after every step:

> 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

From the 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.

  • Related