Convert java.util.Date to java.time.LocalDate
To convert a java.util.Date
object to a java.time.LocalDate
object, you can use the java.time.Instant
class to represent the date as an instant in time, and then use the java.time.LocalDateTime
class to convert the instant to a date and time in the local time zone. Finally, you can use the java.time.LocalDateTime.toLocalDate()
method to extract the local date from the local date and time.
Here's an example of how to do the conversion:
import java.util.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Create a Date object
Date date = new Date();
// Convert Date to Instant
Instant instant = date.toInstant();
// Convert Instant to LocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// Convert LocalDateTime to LocalDate
LocalDate localDate = localDateTime.toLocalDate();
// Print the LocalDate
System.out.println(localDate);
}
}
This will print the local date corresponding to the given java.util.Date
object.
Note: In Java 8 and later, you can use the java.time.ZoneId.systemDefault()
method to get the default time zone of the system. If you are using an earlier version of Java, you can use the java.util.TimeZone.getDefault()
method to get the default time zone, and then pass it to the java.time.ZoneId.of()
method to get a ZoneId
object.