1

I have a string with the following format "2018-04-24 11:56:27+0000". This is a UTC time and it should be converted to local time.

I want to create a Date Object that represents the same date in Chrome, Firefox, Edge and IE (all latest). This format works for all browsers except IE. I use it like

new Date("2018-04-24 11:56:27+0000")

I can not change the format because it comes from another service (I only could reformat it in my frontend logic). Is there a way to create a Date Object from this also in IE, or is there any conversion algorithm to convert this format to some IE compatible format in Javascript and only for IE?

Javascript Invalid Date Error in Internet Explorer does not solve my problem because they use local time, not UTC in constructos. I can't do the same with UTC times

bpoiss
  • 13,673
  • 3
  • 35
  • 49
  • 3
    Which IE version are we talking about? – getjackx Apr 24 '18 at 13:43
  • If you know *for sure* that you only get UTC times then `let [date, t] = str.split(' '); let [time] = t.split(/[+\-]/); new Date(\`${date}T${time}Z\`);` should work. After being run through babel of course. – Jared Smith Apr 24 '18 at 13:46
  • Have a look at this https://stackoverflow.com/questions/13091523/javascript-invalid-date-error-in-internet-explorer – Antonio Pangallo Apr 24 '18 at 13:49
  • @AntonioPangallo if a question is a duplicate you can flag it as such, even (I think) at your rep level. – Jared Smith Apr 24 '18 at 14:00
  • @getjackx all browsers latest version – bpoiss Apr 25 '18 at 05:21
  • @AntonioPangallo I already found this question, but they use local time to create the Date object not UTC time. I can not find a way to this with UTC time string in constructor that works in all listed browsers – bpoiss Apr 25 '18 at 05:24
  • @bpoiss—the issue is that the string does not conform to the [format specified in ECMA-262](http://ecma-international.org/ecma-262/8.0/#sec-date-time-string-format), so parsing using the built-in parser is implementation dependent. Either parse it yourself (2 lines of code) or use a library. – RobG Apr 25 '18 at 08:30
  • @JaredSmith—vs the much shorter and more compatible `var b = str.split(/\D/);new Date(Date.UTC(b[0],--b[1],b[2],b[3],b[4],b[5]));`. ;-) – RobG Apr 25 '18 at 08:46

0 Answers0