Instant until() Method in Java


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("
The 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("
The time between two instant objects in hours is: " + time);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

487 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements