Date & Time API
TL;DR
- Java 8 introduced a completely new Date and Time API in the
java.timepackage. - It was created to replace the notoriously flawed
java.util.Dateandjava.util.Calendar. - Key concepts: All new classes are Immutable and Thread-Safe.
Concept
The old Date class had massive issues: it wasn’t thread-safe (causing bugs in multithreaded web apps), it was mutable (anyone could change the date object passed to them), and its numbering was bizarre (Months were 0-indexed, but Days were 1-indexed).
The new Java 8 API solves all this. It separates time handling into distinct classes:
LocalDate: Date without time or timezone (e.g., “2023-10-31”).LocalTime: Time without date or timezone (e.g., “14:30:00”).LocalDateTime: Both date and time, no timezone.ZonedDateTime: Date and time with a specific timezone (e.g., UTC or EST).Duration/Period: Used to represent an amount of time between two points.
Examples
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateTimeExample {
public static void main(String[] args) {
// 1. Get Current Date & Time
LocalDate today = LocalDate.now();
System.out.println("Today: " + today); // 2023-10-31
// 2. Create specific Date
LocalDate birthday = LocalDate.of(1990, 5, 15);
// 3. Immutability & Manipulation
// .plusDays returns a NEW object. It doesn't modify 'today'
LocalDate nextWeek = today.plusDays(7);
System.out.println("Next week: " + nextWeek);
// 4. Calculating differences
long daysAlive = ChronoUnit.DAYS.between(birthday, today);
System.out.println("Days alive: " + daysAlive);
// 5. Formatting
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
System.out.println("Formatted: " + now.format(formatter));
}
}
Interview Questions
Q: Why is Immutability important in the new Date/Time API?
A: Immutability guarantees Thread-Safety. Because a LocalDate object cannot be changed once created, you can safely pass it between hundreds of threads in a web server without worrying about synchronized locks or race conditions. If a thread needs to change the date, it creates a brand-new object. This eliminates an entire class of subtle, hard-to-track bugs that plagued java.util.Date.
Q: How do you convert between the old java.util.Date and the new LocalDateTime?
A: Because billions of lines of legacy code still use java.util.Date, the developers added conversion methods.
- From Old to New:
oldDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); - From New to Old:
Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());