3

When googling this, I came across many answers - hence the question.

What is the correct way to parse any xsd:date to a LocalDate in Java?

Here are the ways I have come up with (from googling):

DatatypeFactory.newInstance()
    .newXMLGregorianCalendar(str)
    .toGregorianCalendar()
    .toZonedDateTime()
    .toLocalDate()

Another:

DatatypeConverter.parseDate(str)
    .toInstant()
    .atZone(ZoneId.systemDefault())
    .toLocalDate()

Or perhaps I should be doing something different altogether?

Cheetah
  • 13,785
  • 31
  • 106
  • 190

1 Answers1

2

No, there is no way to correctly convert any xsd:date to LocalDate.

Because xsd:date may have timezone and LocalDate does not have timezone. So either it's not any xsd:date or the conversion is not entirely correct.

If you're OK with losing timezone then I'd just do:

XMLGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(str);
LocalDate localDate = LocalDate.of(cal.getYear(), cal.getMonth(), cal.getDay());

I've seen a couple of answers which do this via GregorianCalendar and ZonedDateTime, but I don't understand why have this indirection if you're up to lose the timezone anyway.

I also think that parsing via XMLGregorianCalendar is better than with DatatypeConverter.parseDate via Calendar since XMLGregorianCalendar is much closer to the lexical value of xsd:date. What you need for LocalDate is just year, month and day so it's reasonable to prefer the shortest path to these values.

lexicore
  • 42,748
  • 17
  • 132
  • 221
  • So my first example would loose timezone information, despite the fact its being converted to a `ZonedDateTime` first and then to a `LocalDate` (which presumably the ZonedDateTime has been coverted to a LocalDateTime first)? – Cheetah Nov 09 '16 at 19:37
  • @Cheetah `LocalDate` [does not store or represent a time or time-zone](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html), period. So of course you lose time zone if you ultimately convert to `LocalDate`, no matter which results you may have had on the way there. – lexicore Nov 09 '16 at 21:17
  • I understand what you are saying. My question is actually incorrect. My question should be: "How best should I pull out the date component from an xsd:date storing in a LocalDate object?" – Cheetah Nov 11 '16 at 11:46
  • @Cheetah I did answer this question, didn't I? – lexicore Nov 11 '16 at 14:57