Search code examples
javajava-timexmlgregoriancalendar

Correct java.time representation of XMLGregorianCalendar


I have a XML element with the following content:

<lastModified>2019-10-09T19:20:45.677+02:00</lastModified>

This is mapped to Java's XMLGregorianCalendar.

I need to convert this value in an appropriate java.time instance.

I am a little confused about which java.time class is the "correct" (i.e. lossless) representation of this XMLGregorianCalendar value.

I suppose it should be ZonedDateTime or is OffsetDateTime the better choice?


Solution

  • The String you have ("2019-10-09T19:20:45.677+02:00") is in an ISO format that doesn't even need an extra formatter in order to parse it. The main reason for the use of an OffsetDateTime are the last 6 characters: +02:00, which denote an offset of 2 hours from UTC (more than just one time zone may actually have this offset at the same time).

    You can convert this value into the proper java.time instance like this, for example:

    public static void main(String[] args) throws DatatypeConfigurationException {
        // your example datetime
        String lastModified = "2019-10-09T19:20:45.677+02:00";
        // create an XMLGregorianCalendar for example purpose
        XMLGregorianCalendar xmlGC = DatatypeFactory.newInstance()
                                                    .newXMLGregorianCalendar(lastModified);
        // print it once in order to see the values
        System.out.println("XMLGregorianCalendar: " + xmlGC.toString());
        // parse its toString() method to an OffsetDateTime
        OffsetDateTime lastModOdt = OffsetDateTime.parse(xmlGC.toString());
        // format the content of the OffsetDateTime in ISO standard
        System.out.println("OffsetDateTime:       " 
                + lastModOdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    }
    

    Output:

    XMLGregorianCalendar: 2019-10-09T19:20:45.677+02:00
    OffsetDateTime:       2019-10-09T19:20:45.677+02:00
    

    This should be correct (lossless enough by losing no information).