LocalDate, LocalTime & LocalDateTime
Creating, reading, and manipulating dates and times — and why every method returns a new object.
The java.time API
Java 8 replaced the old, error-prone Date and Calendar classes with the java.time package. The three workhorse types:
- LocalDate — a date (year, month, day) with no time and no timezone.
- LocalTime — a time of day with no date and no timezone.
- LocalDateTime — both combined.
All three are created the same two ways:
LocalDate today = LocalDate.now(); // current date from system clock
LocalDate birthday = LocalDate.of(1990, 6, 15); // year, month (1–12), day
LocalTime noon = LocalTime.of(12, 0); // hour, minute
LocalDateTime dt = LocalDateTime.of(today, noon);
Immutability — the most important property: every manipulation method returns a new object; the original is never changed:
LocalDate tomorrow = today.plusDays(1); // today is still today
LocalDate lastYear = today.minusYears(1);
LocalDate fixed = today.withYear(2000); // replace the year component
Comparison and inspection:
boolean before = birthday.isBefore(today);
boolean after = birthday.isAfter(today);
DayOfWeek dow = today.getDayOfWeek(); // MONDAY, TUESDAY, …
int day = today.getDayOfMonth();
Month month = today.getMonth(); // JANUARY, …