Instant compareTo() method in Java


Two Instant objects can be compared using the compareTo() method in the Instant class in Java. This method requires a single parameter i.e. the Instant object to be compared.

If the first Instant object is greater than the second Instant object it returns a positive number, if the first Instant object is lesser than the second Instant object it returns a negative number and if both the Instant objects are equal it returns zero.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.*;
public class Demo {
   public static void main(String[] args) {
      Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z");
      Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z");
      System.out.println("The first Instant object is: " + i1);
      System.out.println("The second Instant object is: " + i2);
      int val = i1.compareTo(i2);
      if(val > 0)
         System.out.println("
The first Instant object is greater than the second Instant object");       else if(val < 0)          System.out.println("
The first Instant object is lesser than the second Instant object");       else          System.out.println("
The Instant objects are equal");    } }

Output

The first Instant object is: 2019-01-13T18:35:19Z
The second Instant object is: 2019-01-13T16:10:35Z

The first Instant object is greater than the second Instant object

Now let us understand the above program.

First the two Instant objects are displayed. Then they are compared using the compareTo() method and the result is displayed using if else statement. A code snippet that demonstrates this is as follows:

Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z");
Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z");
System.out.println("The first Instant object is: " + i1);
System.out.println("The second Instant object is: " + i2);
int val = i1.compareTo(i2);
if(val > 0)
   System.out.println("
The first Instant object is greater than the second Instant object"); else if(val < 0)    System.out.println("
The first Instant object is lesser than the second Instant object"); else System.out.println("
The Instant objects are equal");

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements