Create a Date from day, month, year in JavaScript

avatar

Borislav Hadzhiev

Wed Jan 26 20222 min read

Create a Date from day, month, year in JavaScript #

Use the Date() constructor to create a date from the day, month and year values, e.g. const date = new Date(2022, 0, 24). The Date() constructor takes the year, a zero-based value for the month and the day as parameters and returns a Date object.

index.js
const date = new Date(2022, 0, 24); // 👇️ Mon Jan 24 2022 00:00:00 console.log(date);

The 3 parameters we passed to the Date() constructor are:

  1. year - an integer that represents the year, e.g. 2022.
  2. monthIndex - a zero-based value that represents the month. For example, January is 0, February is 1, March is 2, etc.
  3. day - an integer that represents the day of the month.
In the example, we passed a value of 0 for the month, which is January.

If you have the value for the month as a one-based value (January = 1), then subtract 1 when passing it to the Date() constructor.

index.js
const str = '2022-01-24'; const [year, month, day] = str.split('-'); const date = new Date(+year, month - 1, day); // 👇️ Mon Jan 24 2022 00:00:00 console.log(date);

We have a date string that is formatted as YYYY-MM-DD in the example.

We split the string on each hyphen to get the values for the year, month and day.

index.js
const str = '2022-01-24'; // 👇️ ['2022', '01', '24'] console.log(str.split('-'));
Because the date string uses a one-based value for the month, we have to subtract 1 when passing the month to the Date() constructor.

Note that the Date() constructor automatically rolls the date over if necessary.

index.js
const date = new Date(2022, 1, 29); // 👇️ Tue Mar 01 2022 00:00:00 console.log(date);

In the example, we passed 2022 as the year, 1 (February) as the month and 29 as the day of the month.

Because February does not have 29 days in 2022, the Date object automatically adjusted the date to the 1st of March.

Use the search field on my Home Page to filter through my more than 1,000 articles.