Sub topic 5
Combining Date and Time with LocalDateTime
A LocalDate holds a calendar date. A LocalTime holds a time of day. Many real tasks need both at once: a meeting on 1 July at 9:30, or a shop that opens on Saturday at 10:00. LocalDateTime covers these cases. It is a class that holds a date and a time together in one object.
This chapter shows how to create a LocalDateTime, how to read its parts, how to change it, and how to compare two of them. It also covers the one thing it cannot do, which is the most common source of bugs.
What LocalDateTime Is
LocalDateTime stores a year, month, day, hour, minute, second, and nanosecond. A nanosecond is one billionth of a second. When you print it, the date and time are joined by the letter T, like 2024-07-01T09:30. This layout follows ISO 8601, an international standard for writing dates and times.
The word "local" means the value has no time zone. A time zone is a region's rule for its clock, such as New York time or Tokyo time. 2024-07-01T09:30 says "9:30 on 1 July" without saying where. It is like a time written on a wall calendar.
Like every java.time type, LocalDateTime is immutable. Immutable means it cannot change after it is created. Methods that seem to change it return a new object, so you must keep the result.
Creating a LocalDateTime
You can build a LocalDateTime from numbers, from a date and a time you already have, or from text.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
public class CreateDateTime {
public static void main(String[] args) {
LocalDateTime a = LocalDateTime.of(2024, Month.JULY, 1, 9, 30);
LocalDateTime b = LocalDateTime.of(2024, 7, 1, 9, 30, 15);
LocalDate date = LocalDate.of(2024, 7, 1);
LocalTime time = LocalTime.of(9, 30);
LocalDateTime c = LocalDateTime.of(date, time);
LocalDateTime d = date.atTime(18, 0);
LocalDateTime e = time.atDate(date);
LocalDateTime f = date.atStartOfDay();
LocalDateTime g = LocalDateTime.parse("2024-07-01T09:30");
System.out.println(a); // 2024-07-01T09:30
System.out.println(b); // 2024-07-01T09:30:15
System.out.println(c.equals(a)); // true
System.out.println(d); // 2024-07-01T18:00
System.out.println(e); // 2024-07-01T09:30
System.out.println(f); // 2024-07-01T00:00
System.out.println(g.equals(a)); // true
}
}Notice that a prints without seconds. When the seconds and nanoseconds are zero, toString leaves them out. The value still holds them as zero.
To get the current date and time, call LocalDateTime.now(). It reads the computer's clock and uses the computer's default time zone, so two servers in different countries will print different results at the same moment. A later chapter shows how to pass a Clock to now() so tests get a fixed value.
Values That Fail
of checks every field. An impossible value throws a DateTimeException, which is an error raised when a date or time is invalid.
| Call | Result |
|---|---|
| `LocalDateTime.of(2024, 2, 29, 12, 0)` | Works, because 2024 is a leap year |
| `LocalDateTime.of(2023, 2, 29, 12, 0)` | Throws: 2023 has no 29 February |
| `LocalDateTime.of(2024, 1, 1, 24, 0)` | Throws: hours run from 0 to 23 |
| `LocalDateTime.parse("2024-07-01 09:30")` | Throws `DateTimeParseException`: the `T` is missing |
The last row catches many beginners. parse with no formatter expects the T. The chapter on DateTimeFormatter shows how to read other layouts.
Reading the Parts
Getter methods return each field. You can also split the object back into a date and a time.
import java.time.LocalDateTime;
public class ReadParts {
public static void main(String[] args) {
LocalDateTime dt = LocalDateTime.of(2024, 12, 31, 23, 45, 10);
System.out.println(dt.getYear()); // 2024
System.out.println(dt.getMonth()); // DECEMBER
System.out.println(dt.getMonthValue()); // 12
System.out.println(dt.getDayOfMonth()); // 31
System.out.println(dt.getDayOfWeek()); // TUESDAY
System.out.println(dt.getHour()); // 23
System.out.println(dt.getMinute()); // 45
System.out.println(dt.getSecond()); // 10
System.out.println(dt.toLocalDate()); // 2024-12-31
System.out.println(dt.toLocalTime()); // 23:45:10
}
}getMonth() returns a Month enum value. An enum is a fixed set of named constants. getMonthValue() returns the number 1 to 12 instead.
Changing a LocalDateTime
There are three families of methods:
plusXandminusXadd or subtract an amount, such asplusHours(3).withXsets one field to a value, such aswithHour(8).truncatedTodrops the smaller fields, such as cutting off minutes and seconds.
Time arithmetic rolls over into the date part. Adding minutes late at night can move you into the next day, month, or even year.
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class ChangeDateTime {
public static void main(String[] args) {
LocalDateTime dt = LocalDateTime.of(2024, 12, 31, 23, 45, 10);
System.out.println(dt.plusMinutes(20)); // 2025-01-01T00:05:10
System.out.println(dt.minusHours(24)); // 2024-12-30T23:45:10
System.out.println(dt.withHour(8)); // 2024-12-31T08:45:10
System.out.println(dt.withDayOfMonth(1)); // 2024-12-01T23:45:10
System.out.println(dt.truncatedTo(ChronoUnit.HOURS)); // 2024-12-31T23:00
LocalDateTime jan31 = LocalDateTime.of(2024, 1, 31, 10, 0);
System.out.println(jan31.plusMonths(1)); // 2024-02-29T10:00
System.out.println(dt); // 2024-12-31T23:45:10, unchanged
}
}The jan31 line shows how month arithmetic handles a day that does not exist. February 2024 has no 31st, so Java picks the last valid day, the 29th. The time of day stays the same.
The final line shows immutability. None of the calls changed dt. Each one returned a new object.
Comparing and Sorting
Use isBefore, isAfter, and isEqual to compare two values. LocalDateTime also implements Comparable, which is the Java interface for objects with a natural order. That means lists of them can be sorted directly.
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CompareDateTime {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2024, 7, 1, 9, 0);
LocalDateTime end = LocalDateTime.of(2024, 7, 1, 17, 30);
System.out.println(start.isBefore(end)); // true
System.out.println(start.isAfter(end)); // false
System.out.println(start.isEqual(LocalDateTime.of(2024, 7, 1, 9, 0))); // true
List<LocalDateTime> events = new ArrayList<>();
events.add(end);
events.add(start);
events.add(LocalDateTime.of(2024, 6, 30, 22, 0));
Collections.sort(events);
System.out.println(events);
// [2024-06-30T22:00, 2024-07-01T09:00, 2024-07-01T17:30]
}
}These comparisons are only meaningful when both values belong to the same place. Comparing a London 9:00 with a Tokyo 9:00 this way says they are equal, which is wrong in real time.
When to Use LocalDateTime
| Situation | Good choice? |
|---|---|
| A birthday party at 7 pm, shown to guests in one town | Yes |
| A store's opening hours, the same in every branch's local time | Yes |
| An alarm that rings at 7:00 wherever the phone is | Yes |
| A log entry recording exactly when a server event happened | No, use Instant |
| A video call between people in different countries | No, use ZonedDateTime |
Use LocalDateTime when the time on the local clock is what matters. Use a zoned type when the exact moment matters.
Exercise
What does LocalDateTime.of(2024, 2, 28, 22, 0).plusHours(3) print, and why?
Show answer
It prints 2024-02-29T01:00. Adding 3 hours to 22:00 passes midnight, so the date rolls forward one day. 2024 is a leap year, so the next day is 29 February.
Exercise
A program runs LocalDateTime dt = LocalDateTime.of(2024, 5, 10, 14, 0); dt.withMinute(30); System.out.println(dt); and prints 2024-05-10T14:00. Why does it not print 14:30, and how do you fix it?
Show answer
LocalDateTime is immutable, so withMinute returns a new object and leaves dt unchanged. The result was thrown away. Keep it instead: dt = dt.withMinute(30); then printing dt shows 2024-05-10T14:30.
Exercise
Write one line that takes LocalDate day = LocalDate.of(2024, 9, 2) and produces a LocalDateTime for 8:15 that morning. Then explain why LocalDateTime.parse("2024-09-02 08:15") fails.
Show answer
LocalDateTime meeting = day.atTime(8, 15); gives 2024-09-02T08:15. The parse call fails with DateTimeParseException because parse without a formatter expects the ISO layout with a T between the date and the time, as in "2024-09-02T08:15".