LocalTime and LocalDateTime
- Java course
- Advanced
- Lesson 20/82
- 5 min
Learn time with LocalTime and LocalDateTime.
LocalTime and LocalDateTime
LocalTime holds a time of day: hour, minute, second. LocalDateTime combines date and time into a single object. Both are immutable.
Example: LocalTime t = LocalTime.of(10, 30); and LocalDateTime dt = LocalDateTime.of(2024, 1, 15, 10, 30);. Methods like plusHours and minusMinutes again return new objects. Use LocalDateTime when both date and time are needed together.
Operating on time values
The plus and minus methods also work on LocalTime and LocalDateTime. For hours you use plusHours, for minutes plusMinutes.
Example: dt.plusHours(2).minusMinutes(15). This adds 2 hours and subtracts 15 minutes. The result is again a new object. Time math is handy for finding when a meeting ends; it handles the 24-hour boundary automatically.
Practice Add two hours to a datetime
Create a datetime with LocalDateTime.of(2024, 1, 15, 10, 30). Add two hours with plusHours(2) and print the result with System.out.println.
Starter code
import java.time.LocalDateTime;
// Create Jan 15 2024 10:30 with LocalDateTime.of
// Add two hours with plusHours
// Print the resultSample solution
import java.time.LocalDateTime;
public class DateTimePlus {
public static void main(String[] args) {
LocalDateTime dt = LocalDateTime.of(2024, 1, 15, 10, 30);
System.out.println(dt.plusHours(2));
}
}Expected output
2024-01-15T12:30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the time classes
| Term | Meaning |
|---|---|
LocalTime |
Time |
LocalDateTime |
Date and time |
LocalTime.now |
Current time |
of |
Specific value |
2 Which class holds both date and time in one object?
- LocalDate
- LocalTime
- Period
- LocalDateTime Correct answer
Explanation: LocalDateTime combines date and time.
3 Complete the LocalTime.of call
LocalTime t = LocalTime.____(10, 30);
LocalTime t = LocalTime.of(10, 30);
Explanation: of creates a specific time.