Date class provides a Date() constructor that accepts day, month and year as arguments. When you call the Date() constructor, you must keep the following things in mind:
let date = new Date(year, month, day);
Dateclass follows zero-based numbering for months. This means January=0, February=1, ..., December=11
Dayparameter represents the day of the month.
Let's understand the process of creating a date from day, month, and year with the help of examples:
1. Suppose you want to represent the 27th of January 2022. In that case, pass 2022 as year, 0 as month, and 27 as day to the
let date = new Date(2022, 0, 27); console.log(date.toString()); //Thu Jan 27 2022
Note: Instead of passing 1 as a month, we have passed 0 because the
Date class follows zero-based numbering.
let date = new Date(2021, 11, 25); console.log(date.toString()); //Sat Dec 25 2021
It is interesting to note that if you pass the value of day which is greater than the maximum number of days in a month. In that case, the Date class will automatically increment the month or year and change the day value to create a valid
In the following example, 40 is passed as day to the Date() constructor. As you know that there are 31 days in March, so the Date class will automatically increment the month and change it to April. Also, it will change the day to the 9th of April.
let date = new Date(2022, 2, 40); console.log(date.toString()); //Sat Apr 09 2022