In Java, you can convert between java.util.Date and java.time.LocalDateTime using the java.time API introduced in Java 8. Here’s how you can perform the conversions:
1. Converting Date to LocalDateTime
You need to use java.time.Instant and java.time.ZoneId to make this conversion. Here’s the process:
package org.kodejava.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateToLocalDateTimeExample {
public static void main(String[] args) {
// Create a Date object
Date date = new Date();
// Convert Date to LocalDateTime
LocalDateTime localDateTime = date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
System.out.println("Date: " + date);
System.out.println("LocalDateTime: " + localDateTime);
}
}
2. Converting LocalDateTime to Date
To convert back from LocalDateTime to Date, again you will make use of Instant and ZoneId.
package org.kodejava.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class LocalDateTimeToDateExample {
public static void main(String[] args) {
// Create a LocalDateTime object
LocalDateTime localDateTime = LocalDateTime.now();
// Convert LocalDateTime to Date
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("LocalDateTime: " + localDateTime);
System.out.println("Date: " + date);
}
}
Explanation:
- Date to LocalDateTime:
Date.toInstant()converts theDateobject into anInstant(a specific point in time)..atZone(ZoneId.systemDefault())adjusts the instant to your system’s default time zone..toLocalDateTime()converts the zoned date-time to aLocalDateTime.
- LocalDateTime to Date:
.atZone(ZoneId.systemDefault())converts aLocalDateTimeinto aZonedDateTime.ZonedDateTime.toInstant()gets anInstantfor the given date and time in the local zone.Date.from(Instant)creates aDateobject from theInstant.
By using these conversions, you can easily switch between the old java.util.Date and the modern java.time.LocalDateTime API.
