Create a Date from day, month, year in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
2 min

banner

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

Use the Date() constructor to create a date from the day, month and year values.

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);

create date from day month year

The code for this article is available on GitHub

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);

subtracting one from the month

The code for this article is available on GitHub

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('-'));
The date string uses a one-based value for the month, so 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);

date constructor automatically rolls date over if necessary

The code for this article is available on GitHub

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

February doesn't have 29 days in 2022, so the Date object automatically adjusted the date to the 1st of March.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev