I am having dates mismatching when pulled from my postgres db. In the database, the date is stored as a Date
value represented as 2023-03-01
, but when I fetch it from the db to use in my JavaScript code, it comes through with a timestamp attached even though Date
representations don't have a timestamp.
In my db the date is 2023-03-01
, but once imported via postgres in my middleware, it is stored as the string 2023-03-01T00:00:00.000Z
.
Now if I need to manipulate that date in my code, I need to create a new Date
object and manipulate it as necessary (i'm using date-fns
), but if I run new Date()
on that value I get Feb 28 instead of Mar 1.
Why does the JavaScript new Date()
method not return the same value when you use a /
vs a -
in the string passed in?
new Date('2023-03-01')
Tue Feb 28 2023 17:00:00 GMT-0700 (Mountain Standard Time)
new Date('2023/03/01')
Wed Mar 01 2023 00:00:00 GMT-0700 (Mountain Standard Time)
When you use a -
to separate the year-month-day, the date is created for UTC time, which for me in CO, makes 3/1 turn into 2/28 or 3/1 Midnight(UTC).
If however you use a /
to separate the year/month/day, the date is created for 3/1 Midnight(MST).
So I've had to create a method to remove the timestamp and then convert all the -
's to be /
in order to get the correct date to manipulate. I just feel like there has to be a better way. Am I missing something here?