×

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

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.