bFren_Sakar
bFren_Sakar

Reputation: 11

How to keep +00:00 instead of Z in XMLGregorianCalendar and OffsetDateTime

I need to serialize(generate Xml String from a Java DTO) and persist the DTO(Oracle DB) using an XSD that has a specific date_time pattern i.e .*(+|-)((0[0-9])|(1[0-3])):[0-5][0-9] which needs to support a date time with offset (2022-02-12T12:49:14+05:45). I am using maven-jaxb plugin to generate XML Java objects and some utility functions to convert the dateTime content. The generated class consists of XMLGregorianCalendar for the dateTime object and I am using OffsetDateTime to map and persist the content.

I can't update the pattern and I am only having issues when the XML date element contains a date like this 2022-02-12T12:49:14+00:00 (with zero offset) where both XMLGregorianCalendar/OffsetDateTime by default converts the offset to Z i.e 2022-02-12T12:49:14Z which is not valid for the pattern.

How can I keep the +00:00 offset while serializing and persisting the DTO? I am using Spring Data JPA to persist the DTO and another issue I am having while persisting the valid OffsetDateTime as the JPA persists the datetime value without offset. String type resolves this but I should not be using the String for datetime. What is the correct type for storing such values?

Here are my mapping functions:

  public static XMLGregorianCalendar toXMLGregorian(OffsetDateTime offsetDateTime) {
        return DATATYPE_FACTORY.newXMLGregorianCalendar(offsetDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    }

 public static OffsetDateTime toOffSetDateTime(XMLGregorianCalendar cal) {
        return cal.toGregorianCalendar().toZonedDateTime().toOffsetDateTime();
    }

I tried to override XMLGregorianCalendar.toXmlFormat() which works but the calendar object still contains the Z instead of +00:00 and serialization fails due to the pattern.

 @Override
    public String toXMLFormat() {
        String text = calendar.toXMLFormat();
        int pos = text.indexOf('Z');
        return pos < 0 ? text : text.substring(0, pos) + "+00:00";
    }

Upvotes: 1

Views: 1038

Answers (0)

Related Questions