Java 8 understanding the LocalDateTime

Java8 understanding the LocalDateTime

In the previous blog we have discussed about the LocalDate and LocalTime, now let’s understand how we can use it together. The composite class called LocalDateTime. It represents the both date and time, but without timezone. So it can be created by passing LocalDate and LocalTime. For example:

LocalDateTime dateTime = LocalDateTime.of(date, time);

And also we can create by passing the exact values:

LocalDateTime dateTime = LocalDateTime.of(2017, Month.FEBRUARY, 12, 11, 20, 12);

We can create the LocalDateTime from the LocalDate.

LocalDate date = LocalDate.of(2017, 3, 18);
LocalDateTime dateTime = date.atTime(time);

atTime() method is overloaded and you can do like this:

LocalDateTime localDateTime1 = date.atTime(12, 15);
LocalDateTime localDateTime2 = date.atTime(12, 15, 14);
LocalDateTime localDateTime3 = date.atTime(12, 15, 14, 15);

And of course from the LocalTime.

LocalTime time = LocalTime.of(11, 20, 12);
LocalDateTime dateTime = time.atDate(LocalDate.of(2017, 3, 18));

And of course we can get the LocalDate and LocalTime from the LocalDateTime.

LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();