java.time.Duration.between() Method Example



Description

The java.time.Duration.between() method obtains a Duration representing the duration between two temporal objects.

Declaration

Following is the declaration for java.time.Duration.between() method.

public static Duration between(Temporal startInclusive, Temporal endExclusive)

Parameters

  • startInclusive − the start instant, inclusive, not null.

  • endExclusive − the end instant, exclusive, not null.

Return Value

a Duration, not null.

Exception

  • DateTimeException − if the seconds between the temporals cannot be obtained.

  • ArithmeticException − if the calculation exceeds the capacity of Duration.

Example

The following example shows the usage of java.time.Duration.between() method.

package com.tutorialspoint;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class DurationDemo {
   public static void main(String[] args) {

      Duration duration = Duration.between(LocalTime.NOON,LocalTime.MAX); 

      LocalDateTime date = LocalDateTime.now();
      System.out.println(date);  

      date = (LocalDateTime)duration.addTo(date);
      System.out.println(date);  
   }
}

Let us compile and run the above program, this will produce the following result −

2017-03-07T15:45:39.456
2017-03-08T03:45:39.455999999
Advertisements