Search code examples
xmljava-8xmlgregoriancalendar

Convert ISO date String WITHOUT colon inside tz-offset to XMLGregorianCalendar


Input Date String : "2016-02-06T00:00:00.000+0100" (No colon in +0100)

Is there any better way of doing it. Wondering if it is an overkill.

public static XMLGregorianCalendar convertStringToXMLGregorianCalendar(final String dateStrInXMLGregorianCalendar) {
        try {
            DateTime dateTime = ISODateTimeFormat.dateTime().parseDateTime(dateStrInXMLGregorianCalendar);
            GregorianCalendar gregCal = new GregorianCalendar(dateTime.getZone().toTimeZone());
            gregCal.setTimeInMillis(dateTime.getMillis());
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregCal);
        } catch (Exception e) {
            throw new RuntimeException(String.format("Exception while converting %s to XMLGregorianCalendar!", dateStrInXMLGregorianCalendar), e);
        }
 }

Solution

  • Maybe this solution which uses only two APIs (both available on Java-8-platforms) and avoids Joda-Time as well as GregorianCalendar:

    String input = "2016-02-06T00:00:00.000+0100";
    OffsetDateTime odt =
        OffsetDateTime.parse(
              input, 
              DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXX"));
    int year = odt.getYear();
    int month = odt.getMonthValue();
    int day = odt.getDayOfMonth();
    int hour = odt.getHour();
    int minute = odt.getMinute();
    int second = odt.getSecond();
    int millisecond = odt.getNano() / 1_000_000;
    int timezone = odt.getOffset().getTotalSeconds() / 60;
    XMLGregorianCalendar xmlcal =
        DatatypeFactory.newInstance().newXMLGregorianCalendar(
            year,
            month,
            day,
            hour,
            minute,
            second,
            millisecond,
            timezone
        );
    System.out.println(xmlcal); // 2016-02-06T00:00:00.000+01:00
    

    More lines of code but two APIs left out which seems to be more reliable and performant for me. For example, your helper method would definitely be insufficient if the year number is before 1582 because XML-Schema requires the proleptic gregorian calendar while your code does not respect this subtile detail.