Module 24: Java Date and Time APIBeginner20 min read
Modern Date & Time (java.time)
Replace legacy Date/Calendar with immutable, thread-safe LocalDate, LocalDateTime, ZonedDateTime, Period, and DateTimeFormatter.
Key Takeaways & Core Concepts
- `LocalDate`: Date without time or timezone (e.g., birthdays, holidays).
- `LocalTime`: Time of day without date.
- `LocalDateTime`: Date + time without timezone.
- `Period` vs `Duration`:
Periodmeasures calendar units (years, months, days);Durationmeasures exact time (hours, minutes, seconds, nanos).
Modern Date & Time (java.time)
### Why java.time (Java 8+) Replaced Date & Calendar Legacy java.util.Date (0-based months, year offset 1900, mutable) and SimpleDateFormat (not thread-safe—sharing one across threads corrupts dates!) caused endless production bugs. java.time classes are immutable, thread-safe, and follow ISO-8601 standards:
- `LocalDate`: Date without time or timezone (e.g., birthdays, holidays).
- `LocalTime`: Time of day without date.
- `LocalDateTime`: Date + time without timezone.
- `ZonedDateTime` & `Instant`: Timezone-aware timestamps and UTC machine epoch instants (always store timestamps in UTC / Instant in databases!).
- `Period` vs `Duration`:
Periodmeasures calendar units (years, months, days);Durationmeasures exact time (hours, minutes, seconds, nanos).
LocalDate, Period & DateTimeFormatter
1import java.time.LocalDate;
2import java.time.Period;
3import java.time.format.DateTimeFormatter;
4
5public class Main {
6 public static void main(String[] args) {
7 LocalDate start = LocalDate.of(2026, 1, 1);
8 LocalDate end = LocalDate.of(2026, 11, 28);
9 Period diff = Period.between(start, end);
10 System.out.println("Formatted: " + end.format(DateTimeFormatter.ofPattern("dd MMM yyyy")));
11 System.out.println("Elapsed: " + diff.getMonths() + " months, " + diff.getDays() + " days");
12 }
13}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: `DateTimeFormatter` is immutable and thread-safe, so you can safely store it in a `static final` constant.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)