JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to create a date from day, month, and year in JavaScript?

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:

  1. The syntax of the Date() constructor is
    let date = new Date(year, month, day);
  2. The year parameter is an integer value, and it represents the year. Examples could be 2022, 2000, etc.
  3. Date class follows zero-based numbering for months. This means January=0, February=1, ..., December=11
  4. Day parameter 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 Date() constructor.

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.

2. Let's say you want to represent the 25th of December 2021 in JavaScript. In that situation, call the Date() constructor and pass 2021 as year, 11 as month, and 25 as day.

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 Date object.

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

Recommended Posts