Write a Java Program to Compare time using compareTo() method


This Java program compares three LocalTime objects and prints out which times are later than the others using the compareTo() method. The program first creates three LocalTime objects using the LocalTime.of() method, passing in hour, minute, and second arguments. It then compares t1 and t2 using the compareTo() method, and prints out whether t1 is later than t2, t2 is later than t1, or they are the same. Similarly, it compares t2 and t3 and prints out whether t2 is later than t3, t3 is later than t2, or they are the same.

The compareTo() method returns an integer value indicating the order of the two LocalTime objects. If the first object is later than the second object, the method returns a positive integer. If the first object is earlier than the second object, the method returns a negative integer. If the two objects are the same, the method returns zero.

If t1 is later than t2, the program will print "Time 1 is Later Than Time 2". If t1 is earlier than t2, the program will print "Time 2 is Later Than Time 1". If t1 and t2 are the same, the program will print "Time 1 and Time 2 are Same". Similarly, if t2 is later than t3, the program will print "Time 2 is Later than Time 3". If t2 is earlier than t3, the program will print "Time 3 is Later than Time 2". If t2 and t3 are the same, the program will print "Time 2 and Time 3 are Same".

Source Code

import java.util.*;
import java.time.*;
public class Time_CompareTo
{
	public static void main(String[] args)
	{
		LocalTime t1;
		LocalTime t2;
		LocalTime t3;
 
		t1 = LocalTime.of(12, 10, 23);
		t2 = LocalTime.of(12, 10, 23);
		t3 = LocalTime.of(10, 45, 46);
 
		if (t1.compareTo(t2) > 0)
		{
			System.out.println("Time 1 is Later Than Time 2");
		}
		else if (t1.compareTo(t2) < 0)
		{
			System.out.println("Time 2 is Later Than Time 1");
		}
		else
		{
			System.out.println("Time 1 and Time 2 are Same");
		}
 
		if (t2.compareTo(t3) > 0)
		{
			System.out.println("Time 2 is Later than Time 3");
		}
		else if (t2.compareTo(t3) < 0)
		{
			System.out.println("Time 3 is Later than Time 2");
		}
		else
		{
			System.out.println("Time 2 and Time 3 are Same");
		}
	}
}

Output

Time 1 and Time 2 are Same
Time 2 is Later than Time 3

Example Programs