In this tutorial, we will see how to convert LocalDate to ZonedDateTime. LocalDate represents the date without time and zone information, ZonedDateTime represents the date with time and zone. To convert the LocalDate to ZonedDateTime, we must add the time and zone id with the local date.
Example 1: Converting the LocalDate given in String format to the ZonedDateTime
In this example, we have date in the string format, we are first parsing the given date in LocalDate and then converting the LocalDate to ZonedDateTime using the atStartOfDay() method.
import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; public class Example { public static void main(String[] args) { //Parsing the given string into a LocalDate LocalDate localDate = LocalDate.parse("2017-07-22"); //Displaying the LocalDate System.out.println("LocalDate is: "+localDate); /* Converting the LocalDate to ZonedDateTime by using the * default zone id and appending the midnight time and default * zone id to the local date using atStartOfDay() method */ ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); //Displaying the ZonedDateTime System.out.println("ZoneDateTime is: "+zonedDateTime); } }
Output:
LocalDate is: 2017-07-22 ZoneDateTime is: 2017-07-22T00:00+05:30[Asia/Kolkata]
Example 2: LocalDate to ZonedDateTime
In the first example we have the date as String. In this example we have the day, month and year information, using which we are creating an instance of LocalDate and then appending the time and zone id with it using the atStartOfDay() method, the same way that we have seen in the above program.
import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; public class Example { public static void main(String[] args) { //Converting the given year, month, date to LocalDate LocalDate localDate = LocalDate.of(2017, 07, 22); //printing the local date System.out.println("LocalDate is: "+localDate); /* Converting the LocalDate to ZonedDateTime the same way that * we have seen in the above example */ ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); //Displaying the output ZonedDateTime System.out.println("ZoneDateTime is: "+zonedDateTime); } }
Output:
LocalDate is: 2017-07-22 ZoneDateTime is: 2017-07-22T00:00+05:30[Asia/Kolkata]
Leave a Reply