Xsd: dateTime in Java OffsetDateTime

To properly handle xs: dateTime with JAXB, I have to write my own converter from String java.time.OffsetDateTime .

As mentioned in the XML schema definition, dateTime was inspired by ISO 8601. I used OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME) to parse xs:dateTime , which works fine, for example.

 "2007-12-03T10:15:30+01:00" //or "2007-12-03T10:15:30Z" 

Unfortunately, in xs:dateTime offset part is declared optional , so parsing the real

 "2016-03-02T17:09:55" 

throws a DateTimeParseException .

Is there a DateTimeFormatter for OffsetDateTime that also handles unzoned xs:dateTime (possibly with a default timezone)?

+5
source share
2 answers

I don't think there is a built-in, but you can make your own using the DateTimeFormatterBuilder class.

You can specify an additional offset enclosed in square brackets, i.e. [XXXXX] (to match "+HH:MM:ss" ). You can then provide a default offset ( parseDefaulting ) in case it is missing. If you want to set UTC by default, you can set 0 to not indicate an offset; and if you want to use the current virtual machine offset by default, you can get it using OffsetDateTime.now().getLong(ChronoField.OFFSET_SECONDS) .

 public static void main(String[] args) { String[] dates = { "2007-12-03T10:15:30+01:00", "2007-12-03T10:15:30Z", "2016-03-02T17:09:55", "2016-03-02T17:09:55Z" }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss[XXXXX]") .parseDefaulting(ChronoField.OFFSET_SECONDS, 0) // or OffsetDateTime.now().getLong(ChronoField.OFFSET_SECONDS) .toFormatter(); for (String date : dates) { System.out.println(OffsetDateTime.parse(date, formatter)); } } 
+5
source

just to show my current solution, which allows an immutable format for the system default in the current dateTime syntax period .

 public static OffsetDateTime parseDateTime(String s) { if (s == null) { return null; } try { return OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME); } catch (DateTimeParseException e) { try { // try to handle zoneless xml dateTime LocalDateTime localDateTime = LocalDateTime.parse(s, DateTimeFormatter.ISO_LOCAL_DATE_TIME); ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(localDateTime); return OffsetDateTime.of(localDateTime.toLocalDate(), localDateTime.toLocalTime(), offset); } catch (Exception fallbackTryException) { throw e; } } } 
+1
source

Source: https://habr.com/ru/post/1244312/


All Articles