Java Duration Class | between() Method with Example

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

Duration Class between() method

  • between() method is available in java.time package.
  • between() method is used to get the duration between the two given objects and here the first object value is inclusive whereas the second object value is exclusive.
  • between() 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.
  • between() method may throw an exception at the time of representing duration between objects.
    • DateTimeException: This exception may throw when the seconds lie in between the given object that couldn't be generated.
    • ArithmeticException: This exception may throw when the calculated result limit exceeds.

Syntax:

    public static Duration between(Temporal st_time, Temporal en_time);

Parameter(s):

  • Temporal st_time – represents the starting endpoint of the returned duration.
  • Temporal en_time – represents the ending endpoint of the returned duration.

Return value:

The return type of this method is Duration, it returns Duration that holds the value between the given two objects.

Example:

// Java program to demonstrate the example 
// of between(Temporal st_time, Temporal en_time)
// method of Duration

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

public class BetweenOfDuration {
    public static void main(String args[]) {
        // Instantiates a Duration and LocalTime object
        Duration du = Duration.ofHours(2);
        LocalTime l_time1 = LocalTime.now();

        // Display l_time1
        System.out.println("l_time1: " + l_time1);

        // adds this object (du) into the 
        // given object (l_time1) i.e. we are adding
        // duration (2 hrs) in l_time1 hours unit
        LocalTime l_time2 = (LocalTime) du.addTo(l_time1);

        // Display l_time2
        System.out.println("l_time2: " + l_time2);

        // returns the duration between 
        // Temporal1 and Temporal2 i.e. difference of
        // 2 hrs in between l_time1 and l_time2
        Duration diff_in_hrs = Duration.between(l_time1, l_time2);
        System.out.println("Duration.between(l_time1,l_time2): " + diff_in_hrs);
    }
}

Output

l_time1: 17:26:11.963034
l_time2: 19:26:11.963034
Duration.between(l_time1,l_time2): PT2H



Comments and Discussions!

Load comments ↻






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