2

new Date('2020-08-18 07:52') is working in Chrome, it returned

Tue Aug 18 2020 07:52:00 GMT+0800 (Malaysia Time)

but safari gave me invalid date? what's the best way to fix this? this bug in safari is breaking my entire app.

Andre Thonas
  • 291
  • 2
  • 15
  • If I remember, Safari supports only [ISO 8601 date format](https://www.w3.org/TR/NOTE-datetime). – Adam Azad Aug 18 '20 at 08:11
  • @AdamAzad I don't have control over the date string, it come from an api. what should I do? – Andre Thonas Aug 18 '20 at 08:16
  • I would do this: `\`${'2020-08-18 07:52'.replace(' ', 'T')}:00\`` – Adam Azad Aug 18 '20 at 08:19
  • @AdamAzad—and you'll still get differences between Safari and others. :-( – RobG Aug 18 '20 at 22:21
  • That format is not supported by ECMA-262 so parsing is implementation dependent. Safari treats it as invalid (likely as a malformed version of a supported format), others don't. The fix is to parse it manually with a simple function or library. – RobG Aug 18 '20 at 22:23

1 Answers1

0

without need for tools/plugins/packages, I would simply separate the received date:

var apiDate = '2020-08-18 07:52'
var [ date, time ] = apiDate.split(' ')
var [ year, month, day ] = date.split('-')
var [ hour, minute ] = time.split(':')

var newDate = new Date(year, month - 1, day, hour, minute, 0)

// Tue Aug 18 2020 07:52:00

I would just be careful about TimeZones, as your date has no time zone description ...

Note from the code above, one might think that subtracting 1 from a string is invalid, but that's the caveats of javascript...

"08" + 1 = "081"
"08" - 1 = 7

if the format is always the same, you can also do:

var apiDate = '2020-08-18 07:52'

var newDate = new Date(`${apiDate.replace(' ', 'T')}:00`)  // '2020-08-18T07:52:00'

// Tue Aug 18 2020 07:52:00
balexandre
  • 73,608
  • 45
  • 233
  • 342