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

Creating LocalDateTime: now, of, parse, and Combining

Master factory methods for LocalDateTime including atTime(), atDate(), and combining existing LocalDate and LocalTime instances.

Creating LocalDateTime: now, of, parse, and Combining

You'll learn how to create LocalDateTime instances using factory methods and by combining existing LocalDate and LocalTime objects.

The Core Idea

Now that you understand LocalDateTime combines date and time, you need practical ways to create instances. Java provides several factory methods: now() for the current moment, of() for explicit values, parse() for strings, and special combining methods like atTime() and atDate() that merge existing date/time objects.

Factory Methods

now() and of()

LocalDateTime current = LocalDateTime.now();

LocalDateTime specific = LocalDateTime.of(2024, 3, 15, 14, 30);
LocalDateTime withSeconds = LocalDateTime.of(2024, 3, 15, 14, 30, 45);
LocalDateTime withNanos = LocalDateTime.of(2024, 3, 15, 14, 30, 45, 500000000);

parse()

LocalDateTime parsed = LocalDateTime.parse("2024-03-15T14:30:45");

Combining Existing Objects

The real power comes from combining LocalDate and LocalTime:

Using atTime() on LocalDate

LocalDate date = LocalDate.of(2024, 3, 15);
LocalDateTime dateTime1 = date.atTime(14, 30);
LocalDateTime dateTime2 = date.atTime(LocalTime.of(14, 30, 45));

Using atDate() on LocalTime

LocalTime time = LocalTime.of(14, 30);
LocalDateTime dateTime = time.atDate(LocalDate.of(2024, 3, 15));

Using LocalDateTime.of() with Objects

LocalDate date = LocalDate.of(2024, 3, 15);
LocalTime time = LocalTime.of(14, 30);
LocalDateTime combined = LocalDateTime.of(date, time);

Think of these combining methods like assembling puzzle pieces—each piece (date or time) is complete on its own, but atTime() and atDate() snap them together into a complete picture.

Key Takeaway: Create LocalDateTime instances using now(), of(), or parse(), or combine existing LocalDate and LocalTime objects using atTime(), atDate(), or LocalDateTime.of(date, time) for flexible, readable datetime construction.