Java Instant Class | until() Method with Example

Instant Class until() method: Here, we are going to learn about the until() method of Instant Class with its syntax and example.
Submitted by Preeti Jain, on May 28, 2020

Instant Class until() method

  • until() method is available in java.time package.
  • until() method is used to determine the amount of time until other Instant in terms of the given unit.
  • until() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • until() method may throw an exception at the time of representing an Instant.
    • DateTimeException: This exception may throw when the given temporal can’t convert into this Instant.
    • UnsupportedTemporlTypeException: This exception may throw when the given unit is unsupported.

Syntax:

    public long until(Temporal en_ex, TemporalUnit t_unit);

Parameter(s):

  • Temporal en_ex – represents the ending temporal object to convert to an Instant.
  • TemporalUnit t_unit – represents the unit of the returned amount of time.

Return value:

The return type of this method is long, it returns the amount of time between this Instant and the given Instant.

Example:

// Java program to demonstrate the example 
// of until(Temporal en_ex, TemporalUnit t_unit)
// method of Instant

import java.time.*;
import java.time.temporal.*;

public class UntilOfInstant {
    public static void main(String args[]) {
        // Instantiates two Instant
        Instant ins1 = Instant.parse("2006-04-03T20:10:30.60Z");
        Instant ins2 = Instant.parse("2006-04-03T10:10:15.60Z");

        // Display ins1,ins2 
        System.out.println("Instant ins1 and ins2: ");
        System.out.println("ins1: " + ins1);
        System.out.println("ins2: " + ins2);

        System.out.println();

        // Here, this method determines the amount of
        // time of this Instant (ins2) until 
        // another Instant (ins1) in the
        // given unit (SECONDS)
        long until = ins2.until(ins1, ChronoUnit.SECONDS);

        // Display until
        System.out.println("ins2.until(ins1,ChronoUnit.SECONDS): " + until);

        // Here, this method determines the amount of
        // time of this Instant (ins2) until 
        // another Instant (ins1) in the
        // given unit (HOURS)
        until = ins2.until(ins1, ChronoUnit.HOURS);

        // Display until
        System.out.println("ins2.until(ins1,ChronoUnit.HOURS): " + until);
    }
}

Output

Instant ins1 and ins2: 
ins1: 2006-04-03T20:10:30.600Z
ins2: 2006-04-03T10:10:15.600Z

ins2.until(ins1,ChronoUnit.SECONDS): 36015
ins2.until(ins1,ChronoUnit.HOURS): 10


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.