Java Convert Date to LocalDateTime
Tags: Java Date Java LocalDateTime Java 8
In this Java core tutorial we learn how to convert a java.util.Date object to a java.time.LocalDateTime object in Java programming language.
How to convert Date to LocalDateTime in Java
In Java, with a given Date object you can follow these steps to convert it to a LocalDateTime object.
- Step 1: convert Date object to Instant object using the Date.toInstant() method.
- Step 2: Use the LocalDateTime.ofInstant(Instant instant, ZoneId zone) method to convert the above Instant object to LocalDateTime object in system default time zone.
ConvertDateToLocalDateTimeExample1.java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;
public class ConvertDateToLocalDateTimeExample1 {
public static void main(String... args) {
Date date = new Date();
Instant instant = date.toInstant();
ZoneId zoneId = TimeZone.getDefault().toZoneId();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
System.out.println("Date: " + date);
System.out.println("LocalDateTime: " + localDateTime);
}
}
Date: Fri May 20 00:28:08 ICT 2022
LocalDateTime: 2022-05-20T00:28:08.860
Happy Coding 😊
Related Articles
Java Convert String to LocalDateTime
Java Convert String to LocalTime
Java Convert String to LocalDate
Java Convert Date to ZonedDateTime
Java Convert Date to LocalTime
Java Convert Calendar to LocalDateTime