date from iso format
431713
function makeDateFromString(string) {
        var format = 'YYYY-MM-DDT',
            i;
        if (isoRegex.exec(string)) {
            for (i = 0; i < 4; i++) {
                if (isoTimes[i][1].exec(string)) {
                    format += isoTimes[i][0];
                    break;
                }
            }
            return parseTokenTimezone.exec(string) ?
                makeDateFromStringAndFormat(string, format + ' Z') :
                makeDateFromStringAndFormat(string, format);
        }
        return new Date(string);
    }
200554
def isotime(s):
    ""
    if type(s) == type(1):
        return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
    elif type(s) == type(1.0):
        date = int(s)
        msec = s - date
        date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
        return date + "." + repr(msec)[3:]
    elif type(s) == type("") or type(s) == type(u""):
        if s[-1] == "Z":
            s = s[:-1]
        if "." in s:
            (date, msec) = s.split(".")
        else:
            date = s
            msec = "0"
        # Note: no leap-second correction! 
        return calendar.timegm(time.strptime(date, "%Y-%m-%dT%H:%M:%S")) + float("0." + msec)
    else:
        raise TypeError
112931
def to_iso_string(self) -> str:
        
        assert isinstance(self.value, datetime)
        return datetime.isoformat(self.value)
574610
private Calendar getCalendar(String iso8601Date) throws
      InvalidDateException
  {
    // YYYY-MM-DDThh:mm:ss.sTZD
    StringTokenizer st = new StringTokenizer(iso8601Date, "-T:.+Z", true);
    if (!st.hasMoreTokens())
    {
      throw new InvalidDateException("Empty Date");
    }
    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.clear();
    try
    {
      // Year
      if (st.hasMoreTokens())
      {
        int year = Integer.parseInt(st.nextToken());
        calendar.set(Calendar.YEAR, year);
      }
      else
      {
        return calendar;
      }
      // Month
      if (checkValueAndNext(st, "-"))
      {
        int month = Integer.parseInt(st.nextToken()) - 1;
        calendar.set(Calendar.MONTH, month);
      }
      else
      {
        return calendar;
      }
      // Day
      if (checkValueAndNext(st, "-"))
      {
        int day = Integer.parseInt(st.nextToken());
        calendar.set(Calendar.DAY_OF_MONTH, day);
      }
      else
      {
        return calendar;
      }
      // Hour
      if (checkValueAndNext(st, "T"))
      {
        int hour = Integer.parseInt(st.nextToken());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
      }
      else
      {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
      }
      // Minutes
      if (checkValueAndNext(st, ":"))
      {
        int minutes = Integer.parseInt(st.nextToken());
        calendar.set(Calendar.MINUTE, minutes);
      }
      else
      {
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
      }
      if (!st.hasMoreTokens())
      {
        return calendar;
      }
      // Not mandatory now
      // Seconds
      String tok = st.nextToken();
      if (tok.equals(":"))
      { // seconds
        if (st.hasMoreTokens())
        {
          int secondes = Integer.parseInt(st.nextToken());
          calendar.set(Calendar.SECOND, secondes);
          if (!st.hasMoreTokens())
          {
            return calendar;
          }
          // decimal fraction of a second
          tok = st.nextToken();
          if (tok.equals("."))
          {
            String nt = st.nextToken();
            while (nt.length() < 3)
            {
              nt += "0";
            }
            if (nt.length() > 3)
            {
              // check the other part from the decimal fraction to be formed only from digits
              for (int i = 3; i < nt.length(); i++)
              {
                if (!Character.isDigit(nt.charAt(i)))
                {
                  throw new InvalidDateException("Invalid digit in the decimal fraction of a second: " + nt.charAt(i));
                }
              }
            }
            nt = nt.substring(0, 3); //Cut trailing chars..
            int millisec = Integer.parseInt(nt);
            calendar.set(Calendar.MILLISECOND, millisec);
            if (!st.hasMoreTokens())
            {
              return calendar;
            }
            tok = st.nextToken();
          }
          else
          {
            calendar.set(Calendar.MILLISECOND, 0);
          }
        }
        else
        {
          throw new InvalidDateException("No secondes specified");
        }
      }
      else
      {
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
      }
      // Time zone
      if (!tok.equals("Z"))
      { // UTC
        if (!(tok.equals("+") || tok.equals("-")))
        {
          throw new InvalidDateException("only Z, + or - allowed");
        }
        boolean plus = tok.equals("+");
        if (!st.hasMoreTokens())
        {
          throw new InvalidDateException("Missing hour field");
        }
        int tzhour = Integer.parseInt(st.nextToken());
        int tzmin;
        if (checkValueAndNext(st, ":"))
        {
          tzmin = Integer.parseInt(st.nextToken());
        }
        else
        {
          throw new InvalidDateException("Missing minute field");
        }
        if (plus)
        {
          calendar.add(Calendar.HOUR, -tzhour);
          calendar.add(Calendar.MINUTE, -tzmin);
        }
        else
        {
          calendar.add(Calendar.HOUR, tzhour);
          calendar.add(Calendar.MINUTE, tzmin);
        }
      }
      else
      {
        if (st.hasMoreTokens())
        {
          throw new InvalidDateException("Unexpected field at the end of the date field: " + st.nextToken());
        }
      }
    }
    catch (NumberFormatException ex)
    {
      throw new InvalidDateException("[" + ex.getMessage() + "] is not an integer");
    }
    return calendar;
  }
1257482
public static Dater iso(String date) {
		//Converting ISO8601-compliant String to java.util.Date
		return of(DatatypeConverter.parseDateTime(
				Strs.WHITESPACE.removeFrom(checkNotNull(date))));
	}
182484
def _iso_to_gregorian(iso_year, iso_week, iso_day):
    ""
    year_start = _iso_year_start(iso_year)
    return year_start + dt.timedelta(days=iso_day-1, weeks=iso_week-1)
585089
public static Date fromISO8601DateString(String iso8601FormattedDate)
      throws com.fasterxml.jackson.databind.exc.InvalidFormatException {

    SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    // set UTC time zone
    iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {
      return iso8601Format.parse(iso8601FormattedDate);
    } catch (ParseException e) {
      throw new InvalidFormatException("Error parsing as date", iso8601FormattedDate, Date.class);
    }
  }
304689
def iso_string_to_python_datetime(
        isostring: str) -> Optional[datetime.datetime]:
    
    if not isostring:
        return None  # if you parse() an empty string, you get today's date
    return dateutil.parser.parse(isostring)
456198
function iso8601totime($iso8601) {
        /*

         date-time       = full-date "T" full-time

         full-date       = date-fullyear "-" date-month "-" date-mday
         full-time       = partial-time time-offset

         date-fullyear   = 4DIGIT
         date-month      = 2DIGIT  ; 01-12
         date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on
         month/year
         time-hour       = 2DIGIT  ; 00-23
         time-minute     = 2DIGIT  ; 00-59
         time-second     = 2DIGIT  ; 00-59, 00-60 based on leap second rules
         time-secfrac    = "." 1*DIGIT
         time-numoffset  = ("+" / "-") time-hour ":" time-minute
         time-offset     = "Z" / time-numoffset

         partial-time    = time-hour ":" time-minute ":" time-second
                                            [time-secfrac]
         */

        $regs = array();
        /*         [1]        [2]        [3]        [4]        [5]        [6]  */
        if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/', $iso8601, $regs)) {
            return mktime($regs[4],$regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
        }
        // to be done: regex for partial-time...apache webdav mod never returns partial-time

        return false;
    }
1069508
def seconds_to_iso(value)
      return self.class.new('PT0S') if value.zero?

      sign_str = value < 0 ? '-' : ''
      value = value.abs

      y, y_mod = decompose_atom(value, years)
      m, m_mod = decompose_atom(y_mod, months)
      d, d_mod = decompose_atom(m_mod, days)
      h, h_mod = decompose_atom(d_mod, hours)
      mi, mi_mod = decompose_atom(h_mod, minutes)
      s = Seconds.new(mi_mod)

      date = to_date_s(sign_str, y, m, d)
      time = to_time_s(h, mi, s)

      self.class.new(date + time)
    end
424510
def parse_iso8601(text):
    
    parsed = _parse_iso8601_duration(text)
    if parsed is not None:
        return parsed

    m = ISO8601_DT.match(text)
    if not m:
        raise ParserError("Invalid ISO 8601 string")

    ambiguous_date = False
    is_date = False
    is_time = False
    year = 0
    month = 1
    day = 1
    minute = 0
    second = 0
    microsecond = 0
    tzinfo = None

    if m:
        if m.group("date"):
            # A date has been specified
            is_date = True

            if m.group("isocalendar"):
                # We have a ISO 8601 string defined
                # by week number
                if (
                    m.group("weeksep")
                    and not m.group("weekdaysep")
                    and m.group("isoweekday")
                ):
                    raise ParserError("Invalid date string: {}".format(text))

                if not m.group("weeksep") and m.group("weekdaysep"):
                    raise ParserError("Invalid date string: {}".format(text))

                try:
                    date = _get_iso_8601_week(
                        m.group("isoyear"), m.group("isoweek"), m.group("isoweekday")
                    )
                except ParserError:
                    raise
                except ValueError:
                    raise ParserError("Invalid date string: {}".format(text))

                year = date["year"]
                month = date["month"]
                day = date["day"]
            else:
                # We have a classic date representation
                year = int(m.group("year"))

                if not m.group("monthday"):
                    # No month and day
                    month = 1
                    day = 1
                else:
                    if m.group("month") and m.group("day"):
                        # Month and day
                        if not m.group("daysep") and len(m.group("day")) == 1:
                            # Ordinal day
                            ordinal = int(m.group("month") + m.group("day"))
                            leap = is_leap(year)
                            months_offsets = MONTHS_OFFSETS[leap]

                            if ordinal > months_offsets[13]:
                                raise ParserError("Ordinal day is out of range")

                            for i in range(1, 14):
                                if ordinal <= months_offsets[i]:
                                    day = ordinal - months_offsets[i - 1]
                                    month = i - 1

                                    break
                        else:
                            month = int(m.group("month"))
                            day = int(m.group("day"))
                    else:
                        # Only month
                        if not m.group("monthsep"):
                            # The date looks like 201207
                            # which is invalid for a date
                            # But it might be a time in the form hhmmss
                            ambiguous_date = True

                        month = int(m.group("month"))
                        day = 1

        if not m.group("time"):
            # No time has been specified
            if ambiguous_date:
                # We can "safely" assume that the ambiguous date
                # was actually a time in the form hhmmss
                hhmmss = "{}{:0>2}".format(str(year), str(month))

                return datetime.time(int(hhmmss[:2]), int(hhmmss[2:4]), int(hhmmss[4:]))

            return datetime.date(year, month, day)

        if ambiguous_date:
            raise ParserError("Invalid date string: {}".format(text))

        if is_date and not m.group("timesep"):
            raise ParserError("Invalid date string: {}".format(text))

        if not is_date:
            is_time = True

        # Grabbing hh:mm:ss
        hour = int(m.group("hour"))
        minsep = m.group("minsep")

        if m.group("minute"):
            minute = int(m.group("minute"))
        elif minsep:
            raise ParserError("Invalid ISO 8601 time part")

        secsep = m.group("secsep")
        if secsep and not minsep and m.group("minute"):
            # minute/second separator but no hour/minute separator
            raise ParserError("Invalid ISO 8601 time part")

        if m.group("second"):
            if not secsep and minsep:
                # No minute/second separator but hour/minute separator
                raise ParserError("Invalid ISO 8601 time part")

            second = int(m.group("second"))
        elif secsep:
            raise ParserError("Invalid ISO 8601 time part")

        # Grabbing subseconds, if any
        if m.group("subsecondsection"):
            # Limiting to 6 chars
            subsecond = m.group("subsecond")[:6]

            microsecond = int("{:0<6}".format(subsecond))

        # Grabbing timezone, if any
        tz = m.group("tz")
        if tz:
            if tz == "Z":
                offset = 0
            else:
                negative = True if tz.startswith("-") else False
                tz = tz[1:]
                if ":" not in tz:
                    if len(tz) == 2:
                        tz = "{}00".format(tz)

                    off_hour = tz[0:2]
                    off_minute = tz[2:4]
                else:
                    off_hour, off_minute = tz.split(":")

                offset = ((int(off_hour) * 60) + int(off_minute)) * 60

                if negative:
                    offset = -1 * offset

            tzinfo = FixedTimezone(offset)

        if is_time:
            return datetime.time(hour, minute, second, microsecond)

        return datetime.datetime(
            year, month, day, hour, minute, second, microsecond, tzinfo=tzinfo
        )
62183
public static String toISO8601String(final Date date) {
		if (date == null)
			return StringUtils.EMPTY;

		return new SimpleDateFormat(FORMAT_ISO_8601).format(date);
	}
442471
def iso8601_date(d):
    
    if d == values.unset:
        return d
    elif isinstance(d, datetime.datetime):
        return str(d.date())
    elif isinstance(d, datetime.date):
        return str(d)
    elif isinstance(d, str):
        return d
381923
public static String toIso8601(Date date) {
        if (date == null) return null;
        return ISODateTimeFormat.dateTimeNoMillis().withZoneUTC().print(date.getTime());
    }
1047834
def ISO8601Format(dt):
   
   isoStr = dt.strftime('%Y-%m-%dT%H:%M:%S')
   if dt.microsecond:
      isoStr += ('.%06d' % dt.microsecond).rstrip('0')
   if dt.tzinfo:
      tz = dt.strftime('%z')
   else:
      if time.daylight and time.localtime().tm_isdst:
         utcOffset_minutes = -time.altzone / 60
      else:
         utcOffset_minutes = -time.timezone / 60
      tz = "%+.2d%.2d" % (utcOffset_minutes / 60, (abs(utcOffset_minutes) % 60))
   if tz == '+0000':
      return isoStr + 'Z'
   elif tz:
      return isoStr + tz[:3] + ':' + tz[3:]
   else:
      # Local offset is unknown
      return isoStr + '-00:00'
1043149
def iso8601_date(s):
    
    try:
        return datetime.datetime.strptime(s, ISO8601_DATE_FORMAT).replace(tzinfo=pytz.utc).date()
    except (TypeError, ValueError):
        return s
249970
def from_iso_long_date(self, date_str: str) -> datetime:
        
        assert isinstance(date_str, str)
        assert len(date_str) == 19

        self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
        return self.value