Wednesday, July 3, 2024
HomeLanguagesJavaDuration between(Temporal, Temporal) method in Java with Examples

Duration between(Temporal, Temporal) method in Java with Examples

The between(Temporal) method of Duration Class in java.time package is used to get a Duration in between the two Temporal objects passed as the parameter. The first parameter is inclusive whereas the second parameter is exclusive of the calculation. If the objects are of different types, then the duration is calculated based on the type of the first object.

Syntax:

public static Duration between(Temporal startDuration, Temporal endDuration)

Parameters: This method accepts two parameters:

  • startDuration: which is the start Instant to be calculated. It is inclusive in the calculation. It should not be null.
  • endDuration: which is the end Instant to be calculated. It is exclusive in the calculation. It should not be null.

Return Value: This method returns a Duration representing the time passed in between the instants passed as the parameters.

Exception: This method throws:

  • DateTimeException: if the seconds between the temporals cannot be obtained.
  • ArithmeticException: if the calculation exceeds the capacity of Duration.

Below examples illustrate the Duration.between() method:

Example 1:




// Java code to illustrate between() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration using between() method
        Duration duration
            = Duration.between(LocalTime.MIDNIGHT,
                               LocalTime.NOON);
  
        System.out.println(duration.getSeconds());
    }
}


Output:

43200

Example 2:




// Java code to illustrate between() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration using between() method
        Duration duration
            = Duration.between(LocalTime.NOON,
                               LocalTime.MAX);
  
        System.out.println(duration.getSeconds());
    }
}


Output:

43199

Reference: Oracle Doc

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments