0

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?

Kyle Combs
  • 106
  • 1
  • 8
  • One of them is reading in UTC, the other is in your local timezone. – Barmar Mar 01 '23 at 20:23
  • 2
    One of them is valid format according to the spec, the other not and thus implementation dependent. [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/q/51715259) – VLAZ Mar 01 '23 at 20:42
  • ECMAScript *Date* objects are just an offset from the epoch (1 Jan 1970 UTC), so they always represent a particular date and time. There is no date–only or time–only representation (the proposed [*Temporal* object](https://github.com/tc39/proposal-temporal) should fix that). – RobG Mar 02 '23 at 22:20

0 Answers0