0

Date format in database: 2023-08-19T04:03:57

The entry above was made at 12:03 AM EST.

new Date("2023-08-19T04:03:57") = 2023-08-19T08:03:57.000Z

This doesn't give me the intended results. .toLocaleString will give me 4:03 AM EST.

If I manually append the "Z":

new Date("2023-08-19T04:03:57Z") = 2023-08-19T04:03:57.000Z I'm given the intended result and can use localize functions properly.

Why is this happening and is there a better solution that manually appending a "Z" each time I need to use these timestamps on client machines?

madmonkey
  • 83
  • 8
  • The JS Date constructor assumes the input is in the local computer's timezone unless you specify one in the date string afaik. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format this gets into detail – CollinD Aug 19 '23 at 05:08
  • 1
    `2023-08-19T04:03:57` is 04:03 in your local timezone, `2023-08-19T04:03:57Z` is 04:03 in UTC. And as EST currently is UTC-4 (ie four hours behind UTC) These are the for hours difference you observe ... Depending on your requirements, you could just store the local time in your database. But you have to be aware that this might lead to strange results when your clients are moving between timezones. – derpirscher Aug 19 '23 at 05:30
  • As @derpirscher says, "2023-08-19T04:03:57" is parsed as local (i.e. using host regional settings) as there's no offset in the timestamp. "2023-08-19T04:03:57Z" is parsed as UTC because the trailing Z indicates UTC (no offset), per [*ECMA-262*](https://262.ecma-international.org/#sec-date.parse). – RobG Aug 19 '23 at 09:32
  • 1
    Probably a duplicate of [*Date.parse unexpected return string*](https://stackoverflow.com/questions/42148067/date-parse-unexpected-return-string), or [*parsing UTC dates with javascript*](https://stackoverflow.com/questions/75988969/parsing-utc-dates-with-javascript) or even [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). – RobG Aug 19 '23 at 09:41
  • @derpirscher this makes sense, although I this makes me question why the db would store posts in local time? I would assume they would use UTC as that should work properly no matter where the client is? This is the default wordpress database implementation – madmonkey Aug 19 '23 at 14:30
  • 1
    The DB stores exactly that, what you tell it to store ... We don't know your queries nor what data you pass. And we don't know your requirements, so we can't tell you what to store in the database ... – derpirscher Aug 19 '23 at 14:33

0 Answers0