Date and Time API
Java 8 added a clear, safe Date and Time API in java.time. Its objects are immutable, so they never change by accident.
LocalDate: a date (2026-11-19).LocalTime: a time (10:30).LocalDateTime: both.Period/Duration: an amount of days or of time.
The old Date and Calendar classes were confusing (months started at 0!) and objects could change unexpectedly. The java.time API fixed this with clear class names for each need. If you're storing a birthday, use LocalDate; for an alarm time, LocalTime; for the exact moment an order was placed in a global system, Instant or ZonedDateTime (which knows the time zone, such as Asia/Kolkata).
Formatting turns a date into text for users ("19 Nov 2026"); parsing turns user text back into a date. DateTimeFormatter handles both with patterns like dd MMM yyyy.
Example
Methods like
plusDays return a new object. Write date = date.plusDays(1);, otherwise the change is lost.Key points
- Use
LocalDate,LocalTime,LocalDateTimefrom java.time. - They're immutable:
plusDaysreturns a new object. PeriodandDurationmeasure amounts of time.DateTimeFormatterformats and parses dates.
📝 Test yourself
1. Which class holds only a date?
2. Are java.time objects immutable?
3. Fill in the method that adds days to a date:
today.(7)
