2

I'm currently trying to format a DB UTC timestamp to the local timezone. For that I'm trying this:

new Date( "2020-03-13 18:40:45 UTC".replace( /\s/, 'T' ) ) 

First I had this:

new Date( "2020-03-13 18:40:45 UTC" ) 

Which works in Chrome and Firefox but not in Safari. So I did some research and came up with the replace. Because of my replace I'm getting now Invalid Date in every browser. I've now idea why... What can I do to fix this?

Mr. Jo
  • 4,946
  • 6
  • 41
  • 100
  • Does this answer your question? [UTC date in Date() object outputs differently in Safari](https://stackoverflow.com/questions/50515136/utc-date-in-date-object-outputs-differently-in-safari) – Anurag Srivastava Mar 23 '20 at 15:39
  • 1
    @AnuragSrivastava - That's more an answer to the OP's implicit question from before they did the `replace`. :-) This one is more about the "UTC" at the end, since having done the replace it doesn't work at all for them now. – T.J. Crowder Mar 23 '20 at 15:41
  • @AnuragSrivastava No – Mr. Jo Mar 23 '20 at 15:42

1 Answers1

2

Make sure your string is in the officially supported format, since anything else is falling back to "...any implementation-specific heuristics or implementation-specific date formats."

The space needs to be a T, and UTC needs to be Z with no space in front of it. (No need for a regular expression here.)

new Date("2020-03-13 18:40:45 UTC".replace(" ", "T").replace(" UTC", "Z"))

Live Example:

const dt = new Date("2020-03-13 18:40:45 UTC".replace(" ", "T").replace(" UTC", "Z"));
console.log(dt.toISOString());

It would appear that Chrome and Firefox have implementation-specific heuristics/formats that would make them accept it with the space and UTC, but not with the T and UTC. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875