Instant until() Method in Java

Java 8Object Oriented ProgrammingProgramming

The time between two instant objects can be calculated using the until() method in the Instant class in Java. This method requires two parameters i.e. the end instant and the chronological unit to measure the time. It returns the time between two instant objects.

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");
      long time = i1.until(i2, ChronoUnit.HOURS);
      System.out.println("Instant object i1 is: " + i1);
      System.out.println("Instant object i2 is: " + i2);
      System.out.println("\nThe time between two instant objects in hours is: " + time);
   }
}

Output

Instant object i1 is: 2019-01-13T11:45:13Z
Instant object i2 is: 2019-01-13T15:30:12Z
The time between two instant objects in hours is: 3

Now let us understand the above program.

The two instant objects are displayed. Then the time between these two instant objects is calculated using the until() method and displayed. 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");
long time = i1.until(i2, ChronoUnit.HOURS);
System.out.println("Instant object i1 is: " + i1);
System.out.println("Instant object i2 is: " + i2);
System.out.println("\nThe time between two instant objects in hours is: " + time);
raja
Published on 26-Mar-2019 05:12:12
Advertisements