Date and Time API

Site Admin · 11 Sep 2026 · 12 views

The Modern Time API

java.time (Java 8 onward) fixes the old, confusing Date and Calendar classes. Its objects are immutable, so they are safe to share between threads.

LocalDate, LocalTime, LocalDateTime

import java.time.*;
import java.time.format.DateTimeFormatter;

LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime stamp = LocalDateTime.now();

LocalDate meeting = LocalDate.of(2026, 12, 25);
System.out.println(today);
System.out.println(meeting.plusDays(10));  // 2027-01-04
System.out.println(today.isAfter(meeting)); // false

Arithmetic

LocalDate start = LocalDate.of(2026, 1, 1);
start = start.plusMonths(2).plusDays(5);
System.out.println(start);            // 2026-03-06
System.out.println(start.getDayOfWeek());
// Duration between instants
Duration d = Duration.ofHours(2).plusMinutes(30);
System.out.println(d.toMinutes());    // 150

Formatting and Parsing

LocalDate date = LocalDate.of(2026, 9, 11);
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(date.format(f));   // 11 Sep 2026

LocalDate parsed = LocalDate.parse("11/09/2026",
    DateTimeFormatter.ofPattern("dd/MM/yyyy"));

Zoned Times

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(now);  // includes an offset like +05:30

Key Points

  • Use LocalDate/LocalTime/LocalDateTime for most work.
  • The API is immutable and thread safe.
  • Patterns with DateTimeFormatter control the text representation.
Share this post:

Comments (0)

Please login or register to comment.