Java Tutorial · Advanced Java · Lesson 34 of 37
Java Date and Time
Work with LocalDate, LocalDateTime, ZonedDateTime, Duration and formatting.
java.time
The java.time package (Java 8+) has clear, immutable types:
| Class | Holds |
|---|---|
LocalDate |
a date: 2026-10-12 |
LocalTime |
a time: 14:30 |
LocalDateTime |
date + time, no zone |
ZonedDateTime |
date + time + time zone |
Instant |
a point on the UTC timeline |
Duration / Period |
time-based / date-based amounts |
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate release = LocalDate.of(2026, 1, 31);
System.out.println(release.plusDays(10));
System.out.println(release.plusMonths(1)); // clamps to the last day of February
System.out.println(release.getDayOfWeek());
System.out.println(release.isLeapYear());
LocalDate xmas = LocalDate.of(2026, 12, 25);
System.out.println(ChronoUnit.DAYS.between(release, xmas) + " days");
Period p = Period.between(release, xmas);
System.out.println(p.getMonths() + " months " + p.getDays() + " days");
}
}
Output
2026-02-10 2026-02-28 SATURDAY false 328 days 10 months 25 days
Run this on your computer — see “Get Started” for setup.
Formatting and time zones
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime meeting = LocalDateTime.of(2026, 7, 4, 15, 30);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEEE d MMMM yyyy, HH:mm", Locale.ENGLISH);
System.out.println(meeting.format(fmt));
ZonedDateTime london = meeting.atZone(ZoneId.of("Europe/London"));
ZonedDateTime tokyo = london.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
System.out.println(tokyo.toLocalDateTime());
System.out.println(Duration.ofMinutes(135).toHours() + "h " + Duration.ofMinutes(135).toMinutesPart() + "m");
System.out.println(LocalDate.parse("2026-03-15").getMonth());
}
}
Output
Saturday 4 July 2026, 15:30 2026-07-04T23:30 2h 15m MARCH
Run this on your computer — see “Get Started” for setup.
Store Instants (UTC) in databases and convert to a zone only for display. Never use the old java.util.Date in new code.
Test yourself
Which class represents a date without a time or time zone?
DateLocalDateInstantZonedDateTime
Show answer
Answer: LocalDate