×

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to retrieve statistics from a database for a selected date and time or if you need to filter out the facts based totally on date and time.

Using the CompareTo() approach of the LocalTime elegance, evaluate times. The CompareTo() approach of the magnificence compares two LocalTime objects. The primary LocalTime item is the object to examine, and the second object is exceeded as a parameter to her CompareTo() approach to explore this LocalTime object.

Syntax of the compare time method in java: The syntax of the compare time in java is given below:

public int compareTo (LocalTime other)  

Parameters of the compare time method in java: Accepts only a single parameter. LocalTime objects to compare. It must not be null.

Returns value of the compare time method in java: The CompareTo() technique returns three values based on evaluating objects.

  1. Returns a tremendous value if this LocalTime item is extra than the specified LocalTime item.
  2. Returns a negative value if this LocalTime object is less than the selected LocalTime object.
  3. Returns null if this LocalTime item is identical to the desired LocalTime object.

Example 1: Here, we give an example of the compareTo() method in java. The example is shown below:

import java.time.*;
public class CompareTime
{
public static void main(String[] args)
{
LT time1 = LocalTime.parse("05:50:59");
LT time2 = LocalTime.parse("12:10:09");
int value = time1.compareTo(time2);
System.out.println("Int Value:" + value);
if (value > 0)          
System.out.println("LT1 is greater");
else if (value == 0)         
System.out.println("LT1 is equal to" + " LT2");
 else          
System.out.println("LT2 is greater");
sc.close;
}
}

Output: We compile the above program and also run this program. The result is given below:

Int Value:1
LT2 is greater

Example 2: Here, we give another example of the compareTo() method in java. The example is given below:

package javaTpoint.JavaExample; 
import java.time.*;  
import java.util.Scanner;  
public class CompareToExample2 {  
 public static void main(String[] args)  
    {  
        int hr1, hr2, min1, min2, sec1, sec2, yr1, yr2, month1, month2, day1, day2;
        LocalDateTime date1, date2;  
        Scanner sc = new Scanner(System.in);  
   System.out.println("Enter Datetime for initializing the first LocaleDateTime object:");        
System.out.println("Enter the year:");  
        yr1 = sc.nextInt();  
        System.out.println("Enter the month:");  
        month1 = sc.nextInt();  
        System.out.println("Enter the day:");  
        day1 = sc.nextInt();  
        System.out.println("Enter the hours:");  
        hr1 = sc.nextInt();  
        System.out.println("Enter the minutes:");  
        min1 = sc.nextInt();  
        System.out.println("Enter the seconds:");  
        sec1 = sc.nextInt();  
        date1 = LocalDateTime.of(yr1, month1, day1, hour1, min1, sec1);  
        System.out.println("Date1: " + date1);  
System.out.println("Enter Datetime for initializing the second LocaleDateTime object:");  
        System.out.println("Enter the year:");  
        yr2 = sc.nextInt();  
        System.out.println("Enter the month:");  
        month2 = sc.nextInt();  
        System.out.println("Enter the day:");  
        day2 = sc.nextInt();  
        System.out.println("Enter the hours:");  
        hr2 = sc.nextInt();  
        System.out.println("Enter the minutes:");  
        min2 = sc.nextInt();  
        System.out.println("Enter the seconds:");  
        sec2 = sc.nextInt();  
        sc.close();  
        date2 = LocalDateTime.of(yr2, month2, day2, hour2, min2, sec2);  
        System.out.println("Date2: " + date2);  
        int returnVal = date1.compareTo(date2); 
        System.out.println("Value returned by comparTo() method:" + returnVal);  
        if (returnVal > 0) {  
            System.out.println("Date1 is greater than date2.");  
        }else if (returnVal == 0) {  
            System.out.println("Date1 is equal to date2.");  
        }else {  
            System.out.println("Date1 is smaller than date2.");  
        }  
    }  
}  

Output: We compile the above program and also run this program. The result is given below:

Enter Datetime for initializing the first LocaleDateTime object:
Enter the year: 2022
Enter the month: 03
Enter the day: 17
Enter the hours: 12
Enter the minutes: 05
Enter the seconds: 48
Date1: 2022-03-17T12:05:48
Enter Datetime for initializing the second LocaleDateTime object:
Enter the year: 2022
Enter the month: 03
Enter the day: 15
Enter the hours: 10
Enter the minutes: 00
Enter the seconds: 40
Date1: 2022-03-15T10:00:40
Value returned by comparTo() method: 1
Date1 is greater than date2.

So, here we give some examples of the compareTo() method and share the output of these. We also discuss the syntax, parameter, and return value of the compareTo() process in java.


Related Topics

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.