The LocalDate represents only the date without time and zone id, while the LocalDateTime represents date with time, so in order to convert LocalDate to LocalDateTime we must append the time with the LocalDate.
LocalDate to LocalDateTime conversion
There are two methods that we can use to convert LocalDate to LocalDateTime.
Method atStartOfDay(): This method adds midnight time to the LocalDate.
LocalDateTime atTime(int hour, int minutes): This method adds given hour and minutes time to the LocalDate.
LocalDateTime atTime(int hour, int minutes, int seconds): This method adds given hour, minutes and seconds time to the LocalDate.
LocalDateTime atTime(int hour, int minutes, int seconds, int nanoseconds): This method adds given hour, minutes, seconds and nanoseconds to the LocalDate.
import java.time.LocalDate; import java.time.LocalDateTime; public class Example { public static void main(String[] args) { LocalDate date = LocalDate.parse("2017-06-22"); System.out.println("LocalDate is: "+date); /* Converting the LocalDate to LocalDateTime using * atStartOfDay() method. This method adds midnight * time (start of the day time) with the local date. */ LocalDateTime localDateTime1 = date.atStartOfDay(); System.out.println("LocalDateTime Start of the Day: "+ localDateTime1); /* The method atTime(int hour, int minutes) is useful when * we need to append the exact hour and minutes to the date * to convert it into a LocalDateTime. The time is in 24 hour * format */ LocalDateTime localDateTime2 = date.atTime(20,16); System.out.println("LocalDateTime for given hour and min: "+ localDateTime2); /* atTime(int hour, int minutes, int seconds) * hour - the hour-of-day, value range from 0 to 23. * minute - the minute-of-hour, value range from 0 to 59. * second - the second-of-minute, value range from 0 to 59. */ LocalDateTime localDateTime3 = date.atTime(20,16, 40); System.out.println("LocalDateTime for given hour, min, seconds: "+ localDateTime3); /* atTime(int hour, int minutes, int seconds, int nanoseconds) * hour - the hour-of-day, value range from 0 to 23. * minute - the minute-of-hour, value range from 0 to 59. * second - the second-of-minute, value range from 0 to 59. * nanoOfSecond - the nano-of-second, value range from 0 to 999,999,999 */ LocalDateTime localDateTime4 = date.atTime(20,16, 40, 1600); System.out.println("LocalDateTime for given hr, min, sec, nanoseconds: "+ localDateTime4); } }
Output:
LocalDate is: 2017-06-22 LocalDateTime Start of the Day: 2017-06-22T00:00 LocalDateTime for given hour and min: 2017-06-22T20:16 LocalDateTime for given hour, min, seconds: 2017-06-22T20:16:40 LocalDateTime for given hr, min, sec, nanoseconds: 2017-06-22T20:16:40.000001600
Leave a Reply