1

I have

const endDate = new Date(year + "-" + month + "-" + date + "T" + endHour + ":" + endMinute + ":00").toUTCString();

in my code to initialize a date object and then convert it to a UTC string, but it returns Invalid Date on Safari. I also tried "MM/DD/YYYY" format for the date part and it did not work either. The variables used are correct because the code works fine on Chrome.

Xi Liu
  • 559
  • 9
  • 18
  • 2
    what is the exact value of month, date, endHour etc ... do they have leading zeros? e.g. 09 for month not just 9? Also, try adding a `Z` to the end of the string - just because one browser may allow a format doesn't mean they all do – Jaromanda X Sep 03 '20 at 01:45
  • Oh man you're right. It's necessary to keep it double-digit. Thanks! – Xi Liu Sep 03 '20 at 07:26
  • Don't use the built–in parser, it sucks, e.g. Safari will treat YYYY-MM-DDTHH:mm:ss as UTC when it should be local. If you have the date parts, give them directly to the constructor: `new Date(year, month - 1, date, endHour, endMinute).toUTCString()` which is also a lot less to type and avoids parser vagaries. – RobG Sep 03 '20 at 10:27
  • Thanks RobG! That makes it much easier. – Xi Liu Sep 03 '20 at 16:16

0 Answers0