In this tutorial, we will see how to convert Date to LocalDate. The java.util.Date
represents date, time of the day in UTC timezone and java.time.LocalDate
represents only the date, without time and timezone.
java.util.Date - date + time of the day + UTC time zone java.time.LocalDate - only date
Keeping these points in mind, we can convert the Date to Local in the following steps:
1. Convert Date to Instant – because we do not want the time in the LocalDate
2. Get the default timezone – because there is no timezone in LocalDate
3. Convert the date to local date – Instant + default time zone + toLocalDate() = LocalDate
Date to LocalDate conversion
import java.time.LocalDate; import java.time.Instant; import java.time.ZoneId; import java.util.Date; public class Example { public static void main(String[] args) { //Getting the current date Date date = new Date(); System.out.println("Date is: "+date); //Getting the default zone id ZoneId defaultZoneId = ZoneId.systemDefault(); //Converting the date to Instant Instant instant = date.toInstant(); //Converting the Date to LocalDate LocalDate localDate = instant.atZone(defaultZoneId).toLocalDate(); System.out.println("Local Date is: "+localDate); } }
Output:
Date is: Sun Oct 22 21:33:46 IST 2017 Local Date is: 2017-10-22
Leave a Reply