LocalDate, Period and ChronoUnit replace the old Date class: clear, unchangeable values with readable methods.
Java · intermediate · 7 min · 8 steps · free
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class DateTimeDemo {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2025, 1, 30);
LocalDate due = start.plusDays(30); // a new date: LocalDate never changes
DayOfWeek day = due.getDayOfWeek();
long days = ChronoUnit.DAYS.between(start, due);
Period age = Period.between(LocalDate.of(2000, 5, 15), start);
boolean leap = LocalDate.of(2024, 1, 1).isLeapYear();
System.out.println(due + " " + day + " " + days + " " + age.getYears() + " " + leap);
}
}leap is created on the stack with the value true.2025-03-01 SATURDAY 30 24 true.Answer: 2025-02-01. Months roll over correctly.
d.plusDays(5); alone, is d changed?Answer: No. The new date was thrown away.
← Optional: No More null Surprises · var: Local Type Inference →