The Date and Time API (java.time)

LocalDate, Period and ChronoUnit replace the old Date class: clear, unchangeable values with readable methods.

Java · intermediate · 7 min · 8 steps · free

What you'll learn

DateTimeDemo.java

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class DateTimeDemo {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2025, 1, 30);
        LocalDate due = start.plusDays(30);                     // a new date: LocalDate never changes
        DayOfWeek day = due.getDayOfWeek();
        long days = ChronoUnit.DAYS.between(start, due);
        Period age = Period.between(LocalDate.of(2000, 5, 15), start);
        boolean leap = LocalDate.of(2024, 1, 1).isLeapYear();
        System.out.println(due + " " + day + " " + days + " " + age.getYears() + " " + leap);
    }
}

Step by step

  1. A date: 30 January 2025. Months are 1-12, not 0-11 like the old API.
  2. plusDays returns a new date: 1 March 2025 (February has 28 days in 2025).
  3. getDayOfWeek: SATURDAY.
  4. ChronoUnit.DAYS.between counts the days: 30.
  5. Period.between gives years, months and days between two dates.
  6. leap is created on the stack with the value true.
  7. It prints 2025-03-01 SATURDAY 30 24 true.
  8. 2025-03-01, SATURDAY, 30 days, age 24, and 2024 is a leap year.

Common mistakes

Best practices

Key takeaways

Check yourself

LocalDate.of(2025, 1, 31).plusDays(1)?

Answer: 2025-02-01. Months roll over correctly.

After d.plusDays(5); alone, is d changed?

Answer: No. The new date was thrown away.

·

More in Safer APIs