All Articles

Quirk in Date Object in Javascript

What is the difference between the output of these 2 lines of Javscript ?

const date1 = new Date("2021-02-11");
const date2 = new Date("2021/02/11");

To answer this we need to understand how the Date constructor converts the string input to a Date Object.

The Date Object follows a certain set of Parsing guidelines (ISO 8601 etc) on how to parse the date string input. If you pass it in the YYYY-MM-DD, the parser tell it that this is a UTC Date string with the time as 00:00:00 if not provided. This can be verified by looking at the following output in your console window :

new Date().toISOString();

Here the output will be something like : "2021-02-11T17:35:13.191Z", which is the same format as "YYYY-MM-DD".

Now in the second case when you provide hyphens ("2021/02/11") the parser tells it that this is a Locale Time Format String. Hence this will create a date assuming that this string is the time in your local timezone.

Therefore the ouputs of the 2 lines will differ. Even the Dates will differ if, the UTC date is different than your local Date. This will help you the next time you are using the Date object in your app and think about the string implementation you are passing to the Date constructor and its effects.