Borislav Hadzhiev
Wed Jan 26 2022·2 min read
Photo by Camila Cordeiro
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.
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:
year
- an integer that represents the year, e.g. 2022
.monthIndex
- a zero-based value that represents the month. For example,
January is 0
, February is 1
, March is 2
, etc.day
- an integer that represents the day of the month.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.
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.
const str = '2022-01-24'; // 👇️ ['2022', '01', '24'] console.log(str.split('-'));
1
when passing the month to the Date()
constructor.Note that the Date()
constructor automatically rolls the date over if
necessary.
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.