Search code examples
javascriptdateiso8601

Understanding Date.prototype.toISOString() ISO 8601 format?


Quote from MDN:

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively).

  1. When will the second format ±YYYYYY-MM-DDTHH:mm:ss.sssZ be returned?
  2. What means the ±YY in the beginning of ±YYYYYY-MM-DDTHH:mm:ss.sssZ?

Solution

  • As the spec says, it will be returned when the year is before 1 AD:

    const d = new Date()
    // Thu Feb 25 2021 14:49:43 GMT+0200 (Eastern European Standard Time)
    d.setFullYear(-7731)
    // -306129149405605
    console.log(d.toISOString())
    // "-007731-02-25T13:09:54.395Z"

    or suitably far into the future.

    const d = new Date();
    d.setFullYear(11931)
    // 314343550183395
    console.log(d.toISOString())
    // "+011931-02-25T12:49:43.395Z"