Comparison

About

In Java, comparing dates and times is a common task — for example, to check if a deadline has passed, to sort events chronologically, or to filter records within a time range.

Java provides multiple date-time APIs, and the comparison techniques vary slightly based on the API being used.

The most commonly used classes for date and time comparison are:

  • java.util.Date (legacy)

  • java.time.LocalDate, LocalDateTime, ZonedDateTime (Java 8+)

java.util.Date

Methods

  • compareTo(Date anotherDate)

  • before(Date when)

  • after(Date when)

  • equals(Object obj)

Example

import java.util.Date;

Date now = new Date();
Date future = new Date(now.getTime() + 10000); // 10 seconds later

System.out.println(now.before(future));       // true
System.out.println(now.after(future));        // false
System.out.println(now.compareTo(future));    // -1
System.out.println(now.equals(future));       // false

java.util.Calendar

Methods

  • compareTo(Calendar other)

  • before(Object when)

  • after(Object when)

  • equals(Object obj)

Example

java.sql.Timestamp

Methods

  • Inherits from java.util.Date

  • Compares including nanoseconds

Example

java.time (Java 8 and later)

java.time.LocalDate

Example

java.time.LocalTime

Example

java.time.LocalDateTime

Example

java.time.ZonedDateTime

Example

java.time.OffsetDateTime

Example

java.time.instant

Example

java.time.duration

Example

java.time.period

Example

Last updated