Java program to compare time using compareTo() method

Java example to demonstrate how to compare time using compareTo() method?
Submitted by Nidhi, on April 02, 2022

Problem Solution:

In this program, we will create objects of the LocalTime class with the specified time. Then we will compare two times using the compareTo() method and print appropriate messages.

Program/Source Code:

The source code to compare time using the compareTo() method is given below. The given program is compiled and executed successfully.

// Java program to compare time using 
// compareTo() method

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

public class Main {
  public static void main(String[] args) {
    LocalTime time1;
    LocalTime time2;
    LocalTime time3;

    time1 = LocalTime.of(10, 15, 18); //10:15:18
    time2 = LocalTime.of(11, 45, 46); //11:45:46
    time3 = LocalTime.of(11, 45, 46); //11:45:46

    if (time1.compareTo(time2) > 0)
      System.out.println("time1 is later than time2.");
    else if (time1.compareTo(time2) < 0)
      System.out.println("time2 is later than time1.");
    else
      System.out.println("time1 and time2 are same.");

    if (time2.compareTo(time3) > 0)
      System.out.println("time2 is later than time3.");
    else if (time2.compareTo(time3) < 0)
      System.out.println("time3 is later than time2.");
    else
      System.out.println("time2 and time3 are same.");
  }
}

Output:

time2 is later than time1.
time2 and time3 are same.

Explanation:

In the above program, we imported the "java.util.*" package to use the Date class. Here, we created a class Main that contains a static method main(). The main() method is the entry point for the program, here we created three objects of the LocalTime class with the specified time. Then we compared created objects using the compareTo() method and printed appropriate messages.

Java Date and Time Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.