XMLGregorianCalendar to LocalDateTime - Java java.time

Java examples for java.time:LocalDateTime

Description

XMLGregorianCalendar to LocalDateTime

Demo Code


//package com.java2s;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

import javax.xml.datatype.XMLGregorianCalendar;

public class Main {
    public static LocalDateTime toLocalDateTime(
            XMLGregorianCalendar calendar) {
        if (calendar != null) {
            ZonedDateTime zonedDateTime = calendar.toGregorianCalendar()
                    .toZonedDateTime();/*  w ww .j a  v  a  2  s  .com*/
            return ZonedDateTime.ofInstant(zonedDateTime.toInstant(),
                    ZoneId.systemDefault()).toLocalDateTime();
        }
        return null;
    }

    public static LocalDateTime toLocalDateTime(ZonedDateTime zonedDateTime) {
        if (zonedDateTime != null) {
            return zonedDateTime.toLocalDateTime();
        }
        return null;
    }

    public static ZonedDateTime toZonedDateTime(
            XMLGregorianCalendar calendar) {
        if (calendar != null) {
            // This way Time is formed as 1995-01-01T00:00+02:00[Europe/Helsinki]
            //                 and not as 1995-01-01T00:00+02:00[GMT+02:00]
            // HashCodeBuilder handles them differently
            return ZonedDateTime.of(toLocalDateTime(calendar),
                    ZoneId.systemDefault());
        }
        return null;
    }

    public static ZonedDateTime toZonedDateTime(LocalDateTime localDateTime) {
        if (localDateTime != null) {
            return localDateTime.atZone(ZoneId.systemDefault());
        }
        return null;
    }
}

Related Tutorials