TransWikia.com

XMLGregorianCalendar to LocalDateTime

Code Review Asked by MrSmith42 on October 27, 2021

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
    }

One Answer

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

Answered by Tristan on October 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP