From some generated code I get a javax.xml.datatype.XMLGregorianCalendar and I want to convert it to a LocalDateTime without any zone-offset (UTC).

My current code accomplishes it, but I think it must be possible to acheaf the same result in a more elegant (and shorter) way.

    public static LocalDateTime xmlGregorianCalendar2LocalDateTime(XMLGregorianCalendar xgc) {
        // fix the time to UTC:
        final int offsetSeconds = xgc.toGregorianCalendar().toZonedDateTime().getOffset().getTotalSeconds();
        final LocalDateTime localDateTime = xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime(); // this simply ignores the timeZone
        return localDateTime.minusSeconds(offsetSeconds); // ajust according to the time-zone offet

1 Answer 1


Something like :

xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime() ?

If you don't want to just rip off the zone information, but instead get the local time at UTC :

ZonedDateTime utcZoned = xgc.toGregorianCalendar().toZonedDateTime().withZoneSameInstant(ZoneId.of("UTC"));
LocalDateTime ldt = utcZoned.toLocalDateTime();

This answer is from the guy who has written the java.time specifications and implemented them btw : https://stackoverflow.com/questions/29767084/convert-between-localdate-and-xmlgregoriancalendar

  • \$\begingroup\$ As I wrote in the comment of my code, this ignores the zone-offset -> wrong time (if zone is not +00:00). \$\endgroup\$
    – MrSmith42
    Mar 8, 2019 at 7:09
  • \$\begingroup\$ So you just need to convert your zonedDateTime to utcZonedDateTime before converting it to local time, see my completed code. \$\endgroup\$
    – Tristan
    Mar 9, 2019 at 8:30
  • 1
    \$\begingroup\$ Be aware that the conversion from XmlGregorianCalendar to GregorianCalendar has a slight precision loss. Nanoseconds will be dropped. This will be ok in most use cases. \$\endgroup\$
    – Chris
    Jan 20, 2020 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.