Date and Time in Java

Introduction

Legacy java.util.Date and Calendar are largely replaced by java.time (Java 8+). This chapter covers LocalDate, LocalDateTime, ZonedDateTime, and DateTimeFormatter for logs, deadlines, and reports.

Prerequisites

Why java.time

  • Clear types (date vs time vs timezone)
  • Immutable objects
  • Thread-safe formatters

1) LocalDate — Date Only

java
import java.time.LocalDate;
 
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(2010, 5, 17);
 
System.out.println(today.getYear());
System.out.println(today.getMonthValue());
System.out.println(today.getDayOfMonth());
 
LocalDate nextWeek = today.plusDays(7);

2) LocalTime — Time Only

java
import java.time.LocalTime;
 
LocalTime now = LocalTime.now();
LocalTime meeting = LocalTime.of(14, 30);

3) LocalDateTime — Date + Time (No Zone)

java
import java.time.LocalDateTime;
 
LocalDateTime timestamp = LocalDateTime.now();
LocalDateTime deadline = LocalDateTime.of(2026, 12, 31, 23, 59);

4) ZonedDateTime — With Time Zone

java
import java.time.ZoneId;
import java.time.ZonedDateTime;
 
ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
ZonedDateTime utc = ZonedDateTime.now(ZoneId.of("UTC"));

Use zones for user-facing apps across regions.

5) DateTimeFormatter — Format and Parse

java
import java.time.format.DateTimeFormatter;
 
LocalDate date = LocalDate.of(2026, 5, 17);
 
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String text = date.format(formatter);
System.out.println(text);  // 2026-05-17
 
LocalDate parsed = LocalDate.parse("2026-05-17", formatter);

Common patterns:

PatternExample
yyyy-MM-dd2026-05-17
HH:mm:ss14:30
yyyy-MM-dd HH:mm2026-05-17 14

DateTimeParseException on invalid input—handle like other runtime exceptions.

6) Duration and Period

java
import java.time.Duration;
import java.time.Period;
 
Period p = Period.between(LocalDate.of(2026, 1, 1), LocalDate.of(2026, 5, 17));
Duration d = Duration.ofMinutes(90);

Period for calendar days; Duration for time-based amounts.

Real Mini Example: Due Date Check

java
public class DueDateChecker {
    public static void main(String[] args) {
        LocalDate due = LocalDate.parse("2026-06-01");
        LocalDate today = LocalDate.now();
 
        if (today.isAfter(due)) {
            System.out.println("Overdue!");
        } else {
            long daysLeft = java.time.temporal.ChronoUnit.DAYS.between(today, due);
            System.out.println(daysLeft + " days remaining");
        }
    }
}

Common Beginner Mistakes

Using Old Date API in New Code

Prefer java.time unless maintaining legacy libraries.

Ignoring Time Zones for Global Apps

Store UTC in databases; convert for display.

Non-thread-safe SimpleDateFormat

Use DateTimeFormatter instead (immutable).

What’s Next

JSON Handling.

FAQ

How to get timestamp for logs?

Instant.now() for UTC instant; format with DateTimeFormatter.

Convert legacy Date?

date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().

Leap years?

LocalDate handles calendar rules.

Parse user locale dates?

Use DateTimeFormatter with Locale or predefined ISO_LOCAL_DATE.

Combine formatted time with File Handling append mode.