Instant isBefore() method in Java


It can be checked if a particular Instant object is before the other Instant object in a timeline using the isBefore() method in the Instant class in Java. This method requires a single parameter i.e. the Instant object that is to be compared. It returns true if the Instant object is before the other Instant object and false otherwise.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant i1 = Instant.parse("2019-01-13T11:45:13.00Z");
      Instant i2 = Instant.parse("2019-01-13T15:30:12.00Z");
      boolean flag = i1.isBefore(i2);
      System.out.println("Instant object i1 is: " + i1);
      System.out.println("Instant object i2 is: " + i2);
      if(flag)
         System.out.println("
Instant object i1 is before Instant object i2");       else          System.out.println("
Instant object i1 is after Instant object i2");    } }

Output

Instant object i1 is: 2019-01-13T11:45:13Z
Instant object i2 is: 2019-01-13T15:30:12Z
Instant object i1 is before Instant object i2

Now let us understand the above program.

The two instant objects i1 and i2 are displayed. It is checked if the Instant object i1 is before the Instant object i2 in the timeline using the isBefore() method. The returned value is displayed using an if statement. A code snippet that demonstrates this is as follows:

Instant i1 = Instant.parse("2019-01-13T11:45:13.00Z");
Instant i2 = Instant.parse("2019-01-13T15:30:12.00Z");
boolean flag = i1.isBefore(i2);
System.out.println("Instant object i1 is: " + i1);
System.out.println("Instant object i2 is: " + i2);

if(flag)
   System.out.println("
Instant object i1 is before Instant object i2"); else    System.out.println("
Instant object i1 is after Instant object i2");

Updated on: 30-Jul-2019

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements