Compare time in Java

Most of the time we need to compare two date and date-time objects. Date comparison is required when we want to get the data of some specific date and time from the database or to filter the returned data based on date and time.

In order to compare time, we use the compareTo() method of the LocalTime class. The compareTo() method of the class compares two LocalTime objects. The first LocalTime object is one which we want to compare, and the second object is which we pass to the compareTo() method as a parameter and from which we want to compare this LocalTime object.

Syntax:

The compareTo() method of the LocalTime class is as follows:

Parameters:

It accepts only a single parameter, i.e., the LocalTime object, which is going to be compared, and it should not be null.

Returns:

The compareTo() method returns three values based on the comparison of the objects:

  1. It returns a positive value when this LocalTime object is greater than the specified LocalTime object.
  2. It returns a negative value when this LocalTime object is smaller than the specified LocalTime object.
  3. It returns zero when this LocalTime object is equal to the specified LocalTime object.

Let's take some examples to understand how the compareTo() method is used for the comparison of two LocalTime objects.

CompareToExample1.java

Output:

Compare time in Java

Let's take one more example to understand the concept of the compareTo() method. In this example, we will compare two date-time objects by using the compareTo() method.

CompareToExample2.java

Output:

Compare time in Java