Work with dates, times, durations, and formatting using the modern, immutable java.time API.
Why: the old Date and Calendar classes were confusing and error-prone. The java.time package replaced them with clear, immutable types: LocalDate (a date), LocalTime (a time), and LocalDateTime (both).
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime moment = LocalDateTime.now();
System.out.println(today); // e.g. 2026-06-17
System.out.println(now); // e.g. 14:32:05.123Why: use the of() factory methods to make an exact date or time. The values are validated — an impossible date like month 13 throws an exception immediately.
import java.time.LocalDate;
import java.time.Month;
LocalDate launch = LocalDate.of(2026, Month.JULY, 4);
System.out.println(launch.getDayOfWeek()); // SATURDAY
System.out.println(launch.getYear()); // 2026Why: dates are immutable, so methods like plusDays return a NEW date rather than changing the original. Compare with isBefore / isAfter to make scheduling decisions.
import java.time.LocalDate;
LocalDate today = LocalDate.of(2026, 6, 17);
LocalDate dueDate = today.plusWeeks(2).plusDays(3);
System.out.println(dueDate); // 2026-07-04
System.out.println(today.isBefore(dueDate)); // trueWhy: Duration measures time-based gaps (hours, minutes, seconds); Period measures date-based gaps (years, months, days). Use them to answer "how long between these two points?"
import java.time.LocalDate;
import java.time.Period;
LocalDate start = LocalDate.of(2026, 1, 1);
LocalDate end = LocalDate.of(2026, 6, 17);
Period between = Period.between(start, end);
System.out.println(between.getMonths() + " months, "
+ between.getDays() + " days");Why: a DateTimeFormatter turns a date into text in a pattern you choose, and parses text back into a date. Patterns use letters: yyyy year, MM month, dd day, HH hour, mm minute.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
LocalDate date = LocalDate.of(2026, 6, 17);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String text = date.format(fmt); // "17/06/2026"
LocalDate back = LocalDate.parse("25/12/2026", fmt);
System.out.println(text);
System.out.println(back.getDayOfWeek()); // FRIDAY