Java

Module 9: Date & Time API (java.time)

By Utility Zone · 2026-01-27T18:53:36.026387

Phase

Phase 3 – Advanced Concepts

Target Audience

  • Java developers tired of Date and Calendar
  • Backend developers handling time zones and formatting
  • Anyone writing production-grade Java applications

1. Objective of This Module

By the end of this module, you will:

  • Understand problems with old Date/Calendar APIs
  • Use the modern java.time API confidently
  • Handle dates, times, and time zones correctly
  • Format and parse dates safely

2. Problems with Old Date & Calendar API

Before Java 8:

  • java.util.Date was mutable
  • Confusing month indexing (0-based)
  • Poor timezone handling
  • Not thread-safe
  • Hard to read and error-prone
Date date = new Date();

This gives date + time + timezone all mixed together.


3. Introduction to java.time Package

Java 8 introduced java.time, inspired by Joda-Time.

Key principles:

  • Immutable classes
  • Clear separation of date, time, and timezone
  • Thread-safe by design

4. Core Date & Time Classes

LocalDate

Represents date only (no time, no timezone).

LocalDate today = LocalDate.now();
LocalDate dob = LocalDate.of(1995, 5, 20);

LocalTime

Represents time only.

LocalTime now = LocalTime.now();
LocalTime meeting = LocalTime.of(10, 30);

LocalDateTime

Represents date + time (no timezone).

LocalDateTime dateTime = LocalDateTime.now();

5. Working with Time Zones

ZonedDateTime

Represents date + time + timezone.

ZonedDateTime zoned =
    ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

Convert between zones:

ZonedDateTime usTime =
    zoned.withZoneSameInstant(ZoneId.of("America/New_York"));

6. Period & Duration

Period

Used for date-based differences.

Period age =
    Period.between(dob, LocalDate.now());

Duration

Used for time-based differences.

Duration duration =
    Duration.between(startTime, endTime);

7. Formatting & Parsing Dates

DateTimeFormatter

DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern("dd-MM-yyyy");

String formatted =
    LocalDate.now().format(formatter);

LocalDate parsed =
    LocalDate.parse("21-01-2026", formatter);

Thread-safe and reusable.


8. Real-World Use Cases

  • Age calculation
  • Booking systems
  • Logging timestamps
  • Timezone conversion for global apps

9. Common Mistakes

  • Mixing old Date with java.time
  • Ignoring time zones
  • Using LocalDateTime when timezone is required
  • Hardcoding date formats

10. Hands-On Exercises

Exercise 1

Calculate age using LocalDate and Period.

Exercise 2

Convert IST time to US time.

Exercise 3

Parse and format dates using custom patterns.


11. Summary

  • java.time is immutable and thread-safe
  • Choose the right class for the problem
  • Always be explicit about time zones

12. What’s Next?

➡️ Module 10: Parallel Streams & Performance