Convert between LocalDate and LocalDateTime

Learn to convert from LocalDate to LocalDateTime and from LocalDateTime to LocalDate in Java 8.

Java date time

Learn to convert from LocalDate to LocalDateTime and from LocalDateTime to LocalDate in Java 8.

To restate, LocalDate represents a calendar date without time and timezone. LocalDateTime stores the date and time information in the local timeline. It does not have any timezone information.

LocalDateTime = LocalDate + LocalTime

1. LocalDate -> LocalDateTime

To convert a LocalDate instance to LocalDateTime instance, we need to add only the time part in it. For this, we can use either of the given 5 methods of LocalDate class.

  • LocalDateTime atStartOfDay()
  • LocalDateTime atTime(LocalTime time)
  • LocalDateTime atTime(int hour, int minutes)
  • LocalDateTime atTime(int hour, int minutes, int seconds)
  • LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond)

The method atStartOfDay() returns a LocalDateTime formed from the given date at the time of midnight, 00:00, at the start of the given date.

For all other methods, we provide the specific time in method arguments.

  • hour – the hour-of-day to use, from 0 to 23
  • minute – the minute-of-hour to use, from 0 to 59
  • second – the second-of-minute to represent, from 0 to 59
  • nanoOfSecond – the nano-of-second to represent, from 0 to 999,999,999

Java program to convert a LocalDate instance to LocalDateTime instance.

LocalDate localDate = LocalDate.parse("2019-01-04");

//Beginning of the day
LocalDateTime localDateTime1 = localDate.atStartOfDay();
System.out.println(localDateTime1);

//Current time
LocalDateTime localDateTime2 = localDate.atTime(LocalTime.now());
System.out.println(localDateTime2);

//Specific time
LocalDateTime localDateTime3 = localDate.atTime(04, 30, 56);
System.out.println(localDateTime3);

Program output.

2019-01-04T00:00
2019-01-04T18:31:21.936
2019-01-04T04:30:56

2. LocalDateTime -> LocalDate

To convert LocalDateTime to LocalDate instance, use toLocalDate() method. It returns a LocalDate with the same year, month and day as in the original localdatetime object.

LocalDateTime localDateTime = LocalDateTime.now();

LocalDate localDate = localDateTime.toLocalDate();

System.out.println(localDate);

Program output.

2019-04-01

Happy Learning !!

Sourcecode on Github

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.