×

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

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

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.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.