Nearby lessons

16 of 125

Java - Date and Time API

📌 What You Will Learn
  • Lambda expressions — the big change
  • Functional interfaces
  • Default and static methods in interfaces
  • The four workhorses: Predicate, Function, Consumer, Supplier
  • Method references (::)
  • The Stream API for processing collections
  • Optional — safe null handling
  • The new Date and Time API

Date and Time API is a core concept of the Java language. This lesson explains The New Date and Time API (java.time) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The New Date and Time API (java.time)

The old Date/Calendar classes were confusing and error-prone (month starts at 0, dates are mutable). Java 8 gave us a clean, immutable Date-Time API.

Trainer's Note: Trainer advice: Java 8 features are the top priority for interviews and jobs. Practise writing lambdas, using streams for list processing, and using Optional. These three skills will set you apart from students who know only old-style Java.
Example01
JCode Cell
1import java.time.*;
2import java.time.format.DateTimeFormatter;
3 
4class DateDemo {
5 public static void main(String[] args) {
6 LocalDate today = LocalDate.now();
7 LocalTime now = LocalTime.now();
8 LocalDateTime dt = LocalDateTime.now();
9 
10 System.out.println("Date: " + today);
11 System.out.println("Time: " + now);
12 System.out.println("Date+Time: " + dt);
13 
14 LocalDate later = today.plusDays(10);
15 System.out.println("10 days later: " + later);
16 
17 DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
18 System.out.println("Formatted: " + today.format(fmt));
19 }
20}
Output
Date: 2026-08-05 Time: 10:15:30.123 Date+Time: 2026-08-05T10:15:30.123 10 days later: 2026-08-15 Formatted: 05/08/2026
📝 Key Takeaways
  • Lambda = a function without a name; (params) -> logic.
  • Functional interface = one abstract method, so a lambda can implement it.
  • Interfaces now have default and static methods with bodies.
  • Predicate (test), Function (apply), Consumer (accept), Supplier (get) are the four core functional interfaces.
  • Method references (::) are shorthand for lambdas.
  • Streams process collections with filter/map/sorted/collect pipelines.
  • Optional prevents NullPointerException with orElse/isPresent.
  • java.time (LocalDate, LocalDateTime) replaces the old Date/Calendar cleanly.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1