Date to LocalDateTime - Java java.time

Java examples for java.time:LocalDateTime

Description

Date to LocalDateTime

Demo Code


//package com.java2s;
import java.time.*;
import java.util.Date;

public class Main {
    /**/*from   w w w  . ja  va2s.  com*/
     * Calls {@link #asLocalDateTime(Date, ZoneId)} with the system default time zone.
     */
    public static LocalDateTime asLocalDateTime(Date date) {
        return asLocalDateTime(date, ZoneId.systemDefault());
    }

    /**
     * Creates {@link LocalDateTime} from {@code java.util.Date} or it's subclasses. Null-safe.
     */
    public static LocalDateTime asLocalDateTime(Date date, ZoneId zone) {
        if (date == null)
            return null;

        if (date instanceof java.sql.Timestamp)
            return ((java.sql.Timestamp) date).toLocalDateTime();
        else
            return Instant.ofEpochMilli(date.getTime()).atZone(zone)
                    .toLocalDateTime();
    }
}

Related Tutorials