Sun Jan 23 2022·3 min read
Photo by Farsai Chaikulngamdee
getDate() method might return a wrong date when passing a string to the
Date() constructor, e.g.
new Date(dateString). How date strings are parsed
is implementation dependent and might vary between browsers.
For consistent results when creating a
Date object, pass multiple,
comma-separated values for the year, month, day, hour, minutes and seconds to
// 👇️ formatted as YYYY-MM-DD hh:mm:ss const dateStr = '2022-09-24 07:30:24'; const [dateComponents, timeComponents] = dateStr.split(' '); console.log(dateComponents); // 👉️ 2022-09-22 console.log(timeComponents); // 👉️ 07:30:24 const [year, month, day] = dateComponents.split('-'); const [hours, minutes, seconds] = timeComponents.split(':'); // ✅ Create Date using multiple, comma-separated parameters const date = new Date(+year, +month - 1, +day, +hours, +minutes, +seconds); console.log(date); // 👉️ Sat Sep 24 2022 07:30:24 console.log(date.getDate()); // 👉️ 24
constructor interprets the passed in
Date() strings can vary between
This could be the cause of the
getDate method returning a wrong date.
If you create a date with a date string (without specifying time), you get a date set in UTC.
For example, if you create a
new Date('2022-09-24'), you end up creating a
date for the 24th of September 2022, 12AM UTC.
Dateobject might point to the 23rd of September, instead of the 24th.
If you want to create a date that is in local time with a date string, you need
to include the time, e.g.
Date object using a date string can be quite confusing, so it's
best to use multiple, comma-separated parameters instead.
A safe approach is to pass the
month (January = 0, February = 1,
seconds values as comma-separated
parameters to the constructor.
month(zero-based) and day of the month as parameters when creating the
In the example, we had a date and time string, formatted as
YYYY-MM-DD hh:mm:ss, but this could be any other format.
The first thing we did was split the date and time string on the space, so we can get the date and time components as separate strings.
We also split the time string on each colon and assigned the hours, minutes and seconds to variables.
Notice that we subtracted
1 from the month when passing it to the
Dateconstructor expects a zero-based value, where January = 0, February = 1, March = 2, etc.
We passed all of the parameters to the
Date() constructor to create a
object and got the correct value from the