In this guide, we will see how to convert LocalDate to Date. Before we see the code for the conversion, lets see what’s the difference between Date and LocalDate.
java.util.Date - date + time + timezone java.time.LocalDate - only date
So to convert the LocalDate to Date, we must append the time and timezone info with the date. Keeping this in mind, the steps for the conversion are as follows:
1. Getting the default time zone so we can append the timezone info with the date
2. Calling atStartOfDay() so that we can append the time with the date
3. LocalDate to Date – local date + atStartOfDay() + default time zone + toInstant() = Date
LocalDate to Date conversion
import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; public class Example { public static void main(String[] args) { //default time zone ZoneId defaultZoneId = ZoneId.systemDefault(); //creating the instance of LocalDate using the day, month, year info LocalDate localDate = LocalDate.of(2016, 8, 19); //local date + atStartOfDay() + default time zone + toInstant() = Date Date date = Date.from(localDate.atStartOfDay(defaultZoneId).toInstant()); //Displaying LocalDate and Date System.out.println("LocalDate is: " + localDate); System.out.println("Date is: " + date); } }
Output:
LocalDate is: 2016-08-19 Date is: Fri Aug 19 00:00:00 IST 2016
Leave a Reply