Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating javascript Date object is not working properly

what is the problem and how to fix this ?

> new Date(2022,5,31)
< Fri Jul 01 2022 00:00:00 GMT+0430 (Iran Daylight Time)
> new Date("2022-5-31")
< Tue May 31 2022 00:00:00 GMT+0430 (Iran Daylight Time)

creating Date(2022,5,31) object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Month is 0 indexed, i.e. 0 represents January.
When you pass in a string with explicit date formatting like "2022-5-31" the month is not 0 indexed.

> new Date(2022,5,31)
                ^
              June
                   ^ 
                   31 -> 01 of the next month (Jul)
< Fri Jul 01 2022 00:00:00 GMT+0430 (Iran Daylight Time)

> new Date("2022-5-31")
                 ^
                May
                    ^
                   31 valid day
< Tue May 31 2022 00:00:00 GMT+0430 (Iran Daylight Time)

This becomes explicit when you try putting days of 35, for example:

> console.log(new Date(2022, 05, 35));
< Tue Jul 05 2022 00:00:00 GMT+0100 (British Summer Time)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading