Connvert java.util.Date to java.time.LocalDateTime Example

In this example, we show you different ways to convert java.util.Date into java.time.LocalDateTime.
This is a common task to convert java.util.Date into java.time.LocalDateTime in Java programming.

Connvert java.util.Date to java.time.LocalDateTime Example

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * Class which shows a way to convert java.util.Date into java.time.LocalDateTime.
 * 
 * @author sourcecodeexamples.net
 *
 */
public class DateToLocalDateTimeConverter {

    public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
        return dateToConvert.toInstant()
            .atZone(ZoneId.systemDefault())
            .toLocalDateTime();
    }

    public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
        return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
    }

    public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
        return Instant.ofEpochMilli(dateToConvert.getTime())
            .atZone(ZoneId.systemDefault())
            .toLocalDateTime();
    }

    public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
        return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
    }

    public static void main(String[] args) {
  System.out.println(convertToLocalDateTime(new Date()));
  System.out.println(convertToLocalDateTimeViaSqlTimestamp(new Date()));
  System.out.println(convertToLocalDateTimeViaMilisecond(new Date()));
 }
}
Output:
2019-06-17T15:03:01.765
2019-06-17T15:03:01.856
2019-06-17T15:03:01.857

Reference


Comments