Web Analytics

Date & Time API

Intermediate ~20 min read

Java 8 introduced a new Date and Time API in the java.time package. It cures the headaches of the old java.util.Date.

Main Classes

  • LocalDate: Date without time (e.g., 2023-12-25)
  • LocalTime: Time without date (e.g., 14:30:00)
  • LocalDateTime: Both date and time.
  • ZonedDateTime: Date and time with timezone.

Creating Dates

import java.time.*;

LocalDate today = LocalDate.now();
LocalDate independenceDay = LocalDate.of(1776, Month.JULY, 4);

System.out.println(today); // 202X-MM-DD

Formatting

Use DateTimeFormatter.

import java.time.format.DateTimeFormatter;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = today.format(formatter);

Full Example

Output
Click Run to execute your code

Summary

  • The new API is Immutable and Thread-safe.
  • Use LocalDate/LocalTime for most logic.
  • Use ZonedDateTime only providing timezone support.