Java Date/Time API
Java Date/Time API tests the immutable java.time types, arithmetic, formatting, and time-zone behavior.
Core rules
LocalDate,LocalTime, andLocalDateTimehave no time zone;ZonedDateTimeandOffsetDateTimedo;Instantis a UTC point on the timeline.- All core types are immutable; methods such as
plusDays,withMonth, andtruncatedToreturn new objects. Periodrepresents a date-based amount (years, months, days);Durationrepresents a time-based amount (seconds, nanos). UseChronoUnitfor unit-based arithmetic.DateTimeFormatteris immutable and thread-safe. Patterns are case-sensitive:MMis month,mmis minute,yyyyis year-of-era,HHis 24-hour hour.- Parsing uses
LocalDate.parse(text, formatter); formatting usesdate.format(formatter). Invalid text throwsDateTimeParseException. ZonedDateTimehandles DST gaps and overlaps;withZoneSameInstantpreserves the instant while changing the zone.
Worked example
LocalDate d = LocalDate.of(2020, 2, 29);
LocalDate e = d.plusYears(1);
Period p = Period.between(d, e);
e is 2021-02-28 because 2021 is not a leap year. Period.between gives P11M30D, not P1Y: it counts 11 whole months to 2021-01-29, then 30 days to the clamped end date.
Traps
java.timemonths are 1-12, unlike the 0-basedCalendar.MONTH.Periodis date-based;Durationis time-based and uses seconds/nanos.DateTimeFormatterpatterns are case-sensitive; mixingMMandmmchanges meaning.Instanthas no zone or offset; useatZoneto attach one.LocalDateTimeignores DST transitions; useZonedDateTimefor zone rules.