Lesson 37 / 39
Dates & Times with java.time
Work with dates, times, durations and time zones using the immutable java.time API instead of Date and Calendar.
LocalDate, LocalDateTime and formatting
The java.time classes are immutable and thread-safe. Use LocalDate for dates, LocalDateTime for date plus time and DateTimeFormatter to print or parse.
LocalDate today = LocalDate.now();
LocalDate due = today.plusDays(14);
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(due.format(f));
System.out.println(LocalDate.parse("2026-10-01").getDayOfWeek());Durations, periods and zones
Duration measures time-based amounts, Period date-based amounts and ZonedDateTime carries a time zone.
Duration d = Duration.between(start, end);
System.out.println(d.toMinutes());
Period p = Period.between(LocalDate.of(2026, 1, 1), LocalDate.now());
ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));Store timestamps as Instant (UTC) and convert to a zone only for display. Avoid the legacy Date, Calendar and SimpleDateFormat.
Quick check
Quick check: Which class represents a point on the UTC timeline?
- Instant
- LocalDate
- Period
- SimpleDateFormat
Answer
Instant — Instant is a machine timestamp; convert it to a zone for display.
Final quiz 1 of 8
Final quiz
Quick check: What does javac produce?
- Native machine code
- An .exe file
- Platform-neutral bytecode
- Nothing
Answer
Platform-neutral bytecode — The JVM runs the bytecode.
Final quiz 2 of 8
Final quiz
Quick check: How should you compare String contents?
- ==
- compare with +
- hashCode()
- equals()
Answer
equals() — == compares references.
Final quiz 3 of 8
Final quiz
Quick check: Which class avoids O(n²) string concatenation in loops?
- StringBuilder
- String
- Scanner
- Objects
Answer
StringBuilder — StringBuilder mutates one buffer.
Final quiz 4 of 8
Final quiz
Quick check: What must you do when overriding equals()?
- Make the class final only
- Override hashCode() consistently
- Return null
- Nothing
Answer
Override hashCode() consistently — Equal objects must share a hash code.
Final quiz 5 of 8
Final quiz
Quick check: Which collection stores unique values with fast membership checks?
- ArrayList
- LinkedList
- HashSet
- int[]
Answer
HashSet — HashSet offers average O(1) contains.
Final quiz 6 of 8
Final quiz
Quick check: Which base class should an unchecked custom exception extend?
- Exception
- Throwable
- Error
- RuntimeException
Answer
RuntimeException — Callers are not forced to catch it.
Final quiz 7 of 8
Final quiz
Quick check: What does try-with-resources do?
- Closes AutoCloseable resources automatically
- Skips exceptions
- Starts threads
- Compiles faster
Answer
Closes AutoCloseable resources automatically — Resources close even if an exception occurs.
Final quiz 8 of 8
Final quiz
Quick check: Which java.time class suits a date with no time?
- Instant
- LocalDate
- Duration
- ZonedDateTime
Answer
LocalDate — LocalDate holds year, month and day only.