Javascript date is invalid on iOS Javascript date is invalid on iOS ios ios

Javascript date is invalid on iOS


Your date string is not in a format specified to work with new Date. The only format in the spec is a simplified version of ISO-8601, added in ES5 (2009). Your string isn't in that format, but it's really close. It would also be easy to change it to a format that isn't in the spec, but is universally supported

Four options for you:

  • Use the upcoming Temporal feature (it's now at StageĀ 3)
  • The specified format
  • An unspecified format that's near-universally supported
  • Parse it yourself

Use the upcoming Temporal feature

The Temporal proposal is at StageĀ 3 as of this update in August 2021. You can use it to parse your string, either treating it as UTC or as local time:

Treating the string as UTC:

// (Getting the polyfill)const {Temporal} = temporal;const dateString = "2015-12-31 00:00:00";const instant = Temporal.Instant.from(dateString.replace(" ", "T") + "Z");// Either use the Temporal.Instant directly:console.log(instant.toLocaleString());// ...or get a Date object:const dt = new Date(instant.epochMilliseconds);console.log(dt.toString());
<script src="https://unpkg.com/@js-temporal/polyfill/dist/index.umd.js"></script>