Course contentsShow
← Java
Lesson 1846 of 2,87038. Date and Time API (java.time)Free lesson

Converting Between LocalDate, LocalTime, and LocalDateTime

Learn to convert between temporal types using atTime(), atDate(), toLocalDate(), and toLocalTime() methods.

Converting Between LocalDate, LocalTime, and LocalDateTime

You'll learn how to seamlessly convert between Java's date and time types using built-in conversion methods.

Why Conversion Matters

Sometimes you have a LocalDate (just a date) but need a LocalDateTime (date plus time) to work with timestamps. Other times you might have a full LocalDateTime but only care about the date or time portion. Java provides straightforward methods to move between these types without manually reconstructing objects.

Converting LocalDate to LocalDateTime

Use atTime() to add a time component to a date:

LocalDate date = LocalDate.of(2024, 1, 15);

// Add a specific time
LocalDateTime dateTime1 = date.atTime(14, 30);  // 2:30 PM
LocalDateTime dateTime2 = date.atTime(9, 0, 30);  // 9:00:30 AM

// Add a LocalTime object
LocalTime time = LocalTime.of(18, 45);
LocalDateTime dateTime3 = date.atTime(time);

Converting LocalTime to LocalDateTime

Use atDate() to add a date component to a time:

LocalTime time = LocalTime.of(10, 30);
LocalDate date = LocalDate.of(2024, 1, 15);

LocalDateTime dateTime = time.atDate(date);  // 2024-01-15T10:30

Converting LocalDateTime to Components

Extract just the date or time portion:

LocalDateTime dateTime = LocalDateTime.of(2024, 1, 15, 14, 30);

LocalDate justDate = dateTime.toLocalDate();  // 2024-01-15
LocalTime justTime = dateTime.toLocalTime();  // 14:30

Think of It Like This

Imagine LocalDate is a calendar page, LocalTime is a clock face, and LocalDateTime is both together. The conversion methods are like attaching or detaching the clock from the calendar—you're either combining them or separating them.

Key Takeaway: Use atTime() and atDate() to build LocalDateTime from components, and use toLocalDate() and toLocalTime() to extract components back out—all while maintaining immutability.