×

Compare Two Times in Java

Definition

The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects.

Here we have two objects that have to be compared: the first is a LocalTime object that we want to compare, and the second is an object that we supply as an input to the compareTo() method.

Why do we compare two times in java?

It is a usual feature to compare two date and time objects. When requesting data from a database at a given time and date, or when filtering the data that has been returned based on time and date, date comparison is necessary.

Syntax

The syntax for comparing two times in java by using the LocalTime class's compareTo() method is as follows:

public int compareTo(LocalTime other)

parameters

It takes only one parameter, a LocalTime object that is to be compared, and it must not be null

Returns

  • When this LocalTime object exceeds the LocalTime object that was supplied, it returns a positive result.
  • It produces a negative result when this LocalTime object is smaller than the specified LocalTime object.
  • This LocalTime object returns 0 if it matches the specified LocalTime object.

Examples for comparing two times in java

Example program for comparing time in java

import java.time.*;  
import java.util.Scanner;  


public class Demo {  


    public static void main(String[] args)  
    {  


        int hour1, hour2, min1, min2, sec1, sec2;  
LocalTime time1, time2;  
        Scanner sc = new Scanner(System.in);  


System.out.println("Enter time for initializing the first LocaleTime object:");  
System.out.println("Enter hours:");  
        hour1 = sc.nextInt();  
System.out.println("Enter minutes:");  
        min1 = sc.nextInt();  
System.out.println("Enter seconds:");  
        sec1 = sc.nextInt();  


        time1 = LocalTime.of(hour1, min1, sec1);  


System.out.println("Enter time for initializing the second LocaleTime object:");  
System.out.println("Enter hours:");  
        hour2 = sc.nextInt();  
System.out.println("Enter minutes:");  
        min2 = sc.nextInt();  
System.out.println("Enter seconds:");  
        sec2 = sc.nextInt();  


sc.close();  


        time2 = LocalTime.of(hour2, min2, sec2);  


        int returnVal = time1.compareTo(time2);  


System.out.println("Value returned by comparTo() method:" + returnVal);  


        if (returnVal> 0) {  
System.out.println("time1 is greater than time2.");  
}else if (returnVal == 0) {  
System.out.println("time1 is equal to time2.");  
}else {  
System.out.println("time1 is smaller than time2.");  
        }  
    }  
}  

Output:

C:\javap>javac Demo.java
C:\javap>java Demo
Enter time for initializing the first LocaleTime object:
Enter hours:
4
Enter minutes:
20
Enter seconds:
10
Enter time for initializing the second LocaleTime object:
Enter hours:
4
Enter minutes:
23
Enter seconds:
25
Value returned by compareTo() method:-1
time1 is smaller than time2.

We can compare the two local times by using the following methods

  1. The two local time objects are compared using the compareTo method
  2. The two local time objects are compared using the equality method
  3. Compared if one local time object is before another local time object
  4. Compared if one local time object is after another local time object

They can be explained as

1.The two local time objects are compared using the compareTo method

import java.io.*;
import java.time.LocalTime;
public class CompareLocalTime
 {
    public static void main(String args[])
 {
LocalTime localTime1 = LocalTime.of(6, 30, 4);
LocalTime localTime2 = LocalTime.of(6, 30, 20);


        int compareToResult = localTime1.compareTo(localTime2);


System.out.println("localTime1: " + localTime1);
System.out.println("localTime2: " + localTime2);
System.out.println("localTime1 compareTo localTime2: " + compareToResult);


    }
}

Output:

C:\javap>javac CompareLocalTime.java
C:\javap>java CompareLocalTime
localTime1: 06:30:04
localTime2: 06:30:20
localTime1 compareTo localTime2: -1

2.The two local time objects are compared using the equality method

import java.io.*;
import java.time.LocalTime;
public class CompareLocalTime
{
    public static void main(String args[])
 {
LocalTime localTime1 = LocalTime.of(7, 30, 11);
LocalTime localTime2 = LocalTime.of(7, 30, 12);
LocalTime localTime3 = LocalTime.of(7, 30, 17);


boolean equalsResult1 = localTime1.equals(localTime2);
boolean equalsResult2 = localTime1.equals(localTime3);


System.out.println("localTime1: " + localTime1);
System.out.println("localTime2: " + localTime2);
System.out.println("localTime3: " + localTime3);
System.out.println("localTime1 is equal to localTime2: " + equalsResult1);
System.out.println("localTime1 is equal to localTime3: " + equalsResult2);
    }
}

Output:

C:\javap>javac CompareLocalTime.java
C:\javap>java CompareLocalTime
localTime1: 07:30:11
localTime2: 07:30:12
localTime3: 07:30:17
localTime1 is equal to localTime2: false
localTime1 is equal to localTime3: false

3.Compared if one local time object is before another local time object

import java.io.*;
import java.time.LocalTime;


public class CompareLocalTime
 {
    public static void main(String args[]) 
{
LocalTime localTime1 = LocalTime.of(1, 10, 30);
LocalTime localTime2 = LocalTime.of(2, 20, 40);
LocalTime localTime3 = LocalTime.of(3, 30, 40);


boolean equalsResult1 = localTime1.isBefore(localTime2);
boolean equalsResult2 = localTime1.isBefore(localTime3);


System.out.println("localTime1: " + localTime1);
System.out.println("localTime2: " + localTime2);
System.out.println("localTime3: " + localTime3);
System.out.println("localTime1 is before localTime2: " + equalsResult1);
System.out.println("localTime1 is before localTime3: " + equalsResult2);
    }
}

Output:

C:\javap>javac CompareLocalTime.java
C:\javap>java CompareLocalTime
localTime1: 01:10:30
localTime2: 02:20:40
localTime3: 03:30:40
localTime1 is before localTime2: true
localTime1 is before localTime3: true

4.Compared if one local time object is after another local time object

import java.io.*;
import java.time.LocalTime;
public class CompareLocalTime
 {
    public static void main(String args[]) 
{
LocalTime localTime1 = LocalTime.of(3, 20, 10);
LocalTime localTime2 = LocalTime.of(2, 30, 20);
LocalTime localTime3 = LocalTime.of(4, 10, 30);


boolean equalsResult1 = localTime1.isAfter(localTime2);
boolean equalsResult2 = localTime1.isAfter(localTime3);


System.out.println("localTime1: " + localTime1);
System.out.println("localTime2: " + localTime2);
System.out.println("localTime3: " + localTime3);
System.out.println("localTime1 is after localTime2: " + equalsResult1);
System.out.println("localTime1 is after localTime3: " + equalsResult2);
    }
}

Output:

C:\javap>javac CompareLocalTime.java
C:\javap>java CompareLocalTime
localTime1: 03:20:10
localTime2: 02:30:20
localTime3: 04:10:30
localTime1 is after localTime2: true
localTime1 is after localTime3: false

Related Topics

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.