Home > Software engineering >  Invalid date for Safari and IE fixed but not with negative UTC
Invalid date for Safari and IE fixed but not with negative UTC

Time:11-08

I saw a lot of answers for the date problem with Safari and IE for the date, using replace(/-/g, "/") works like a charm for these cases 2022-11-30 17:00 UTC 0200 but encountered an issue when I had other time zone like this one 2022-11-28 21:56 UTC-0500 it would create an invalid date again, for any browser.

So I'm looking for a solution that would replace the "-" not globally but only in the first word eventually.

Thank you

CodePudding user response:

What about that?

const date = `2022-11-30 17:00 UTC-0200`
const regex = /(\d )-(\d )-(\d )/g
const result = date.replace(regex, '$1/$2/$3')
console.log(result)

CodePudding user response:

You can optionally capture UTC before - and if it is captured, put back the whole match, else, replace - with /:

const text = "2022-11-28 21:56 UTC-0500";
console.log( text.replace(/(UTC)?-/g, (x,y) => y ? x : "/") )

Here,

  • (UTC)?- - matches and captures an optional UTC in Group 1 and then matches a - char
  • (x,y) => y ? x : "/" - if y (Group 1) was matched, put back x (the whole match), else, put / instead of -.

A lookbehind version:

const text = "2022-11-28 21:56 UTC-0500";
console.log( text.replace(/(?<!UTC)-/g, "/") )
// => 2022/11/28 21:56 UTC-0500

(?<!UTC)- matches a - that is not immediately preceded with UTC.

  • Related