Java Duration Class | of() Method with Example

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

Duration Class of() method

  • of() method is available in java.time package.
  • of() method is used to denotes the given amount (amt) in the given unit (t_unit) in this Duration.
  • of() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • of() method may throw an exception at the time of representing Duration.
    • ArithmeticException: This exception may throw when the calculated result value exceeds the limit.
    • DateTimeException: This exception may throw when the given unit is not exact in terms of Duration.

Syntax:

    public static Duration of(long amt, TemporalUnit t_unit);

Parameter(s):

  • long amt – represents the amount in which to use in the given unit.
  • TemporalUnit t_unit – represents the unit by which to measure the amount.

Return value:

The return type of this method is Duration, it returns the Duration that holds the amount (amt) value in the given unit.

Example:

// Java program to demonstrate the example 
// of of(long amt, TemporalUnit t_unit) method 
// of Duration

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

public class OfDuration {
    public static void main(String args[]) {
        long amt = 2;
        ChronoUnit amt_unit = ChronoUnit.MINUTES;

        // represents the given amount
        // in the given unit i.e here amt 2 is
        // represented in minutes like 2M
        Duration du1 = Duration.of(amt, amt_unit);

        // Display du1
        System.out.println("Duration.of(2,minutes): " + du1);

        amt_unit = ChronoUnit.DAYS;

        // represents the given amount
        // in the given unit i.e. here amt 2 is
        // represented in DAYS like 2D i.e. 48H
        Duration du2 = Duration.of(amt, amt_unit);

        // Display du2
        System.out.println("Duration.of(2,days): " + du2);
    }
}

Output

Duration.of(2,minutes): PT2M
Duration.of(2,days): PT48H


Comments and Discussions!

Load comments ↻





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