Java
Summary - Date/time API
Combine LocalDate, Period and DateTimeFormatter to write an age calculator.
Summary - Date/time API
In this group you covered the core classes of the java.time package. LocalDate holds a date, LocalTime a time, LocalDateTime both together. Duration gives hour-based, Period day-based lengths. Instant holds a UTC moment, ZonedDateTime a regional time.
DateTimeFormatter turns dates and times into strings and reads them back. These classes are immutable, which makes math safe; they replace the old Date class in a modern way.
Exercise Age calculation with Period.between
Create a birth date with LocalDate.of(2000, 5, 15) and today with LocalDate.of(2024, 5, 15). Print the age with Period.between(birth, today).getYears() via System.out.println.
Show example solution
import java.time.LocalDate;
import java.time.Period;
public class BirthdayCalc {
public static void main(String[] args) {
LocalDate birth = LocalDate.of(2000, 5, 15);
LocalDate today = LocalDate.of(2024, 5, 15);
System.out.println(Period.between(birth, today).getYears());
}
}
Which class when?
Choosing the right class depends on the question. Use LocalDate for date only, LocalTime for time only, LocalDateTime when both are needed. Pick Instant for global time and ZonedDateTime for regional display.
For lengths, use Period for dates and Duration for times. For display, DateTimeFormatter always works. Avoid the legacy Date and Calendar classes; the java.time package offers a modern, consistent alternative.
Exercise Format and compute a meeting duration
Create start with LocalDateTime.of(2024, 1, 15, 10, 0) and end with LocalDateTime.of(2024, 1, 15, 12, 30). Get the minutes with Duration.between(start, end).toMinutes(). Format the start with DateTimeFormatter.ofPattern("HH:mm"). Print formatted + " - " + minutes + " min" via System.out.println.
Show example solution
import java.time.LocalDateTime;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
public class MeetingDuration {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2024, 1, 15, 10, 0);
LocalDateTime end = LocalDateTime.of(2024, 1, 15, 12, 30);
long minutes = Duration.between(start, end).toMinutes();
DateTimeFormatter f = DateTimeFormatter.ofPattern("HH:mm");
System.out.println(start.format(f) + " - " + minutes + " min");
}
}
Test yourself
-
Which class holds a year-month-day based date range?
- Duration
- Instant
- LocalTime
- Period
Show answer
Period — Period is year-month-day based.
-
Match each class with its behavior
- LocalDate
- Date
- LocalTime
- Time
- Duration
- Hour range
- Instant
- UTC moment
Next lesson: Class<?>