Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | plus() Method with Example
Duration Class plus() method: Here, we are going to learn about the plus() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 16, 2020
Duration Class plus() method
Syntax:
public Duration plus(Duration d);
public Duration plus(long amt, TemporalUnit t_unit);
- plus() method is available in java.time package.
- plus(Duration d) method is used to add the given Duration to this Duration and return the Duration.
- plus(long amt, TemporalUnit t_unit) method is used to add the given amount in the given unit to this Duration and return the Duration.
- These methods may throw an exception at the time of performing addition.
ArithmeticException: This exception may throw when the calculated result exceeds the limit to represent this object.
- These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.
Parameter(s):
-
In the first case, plus(Duration d),
- Duration d – represents the Duration to be added to this Duration.
-
In the first case, plus(long amt, TemporalUnit t_unit),
- long amt – represents the amount in units to be added to this Duration.
- TemporalUnit t_unit – represents the unit to measure the given amount.
Return value:
In both the cases, the return type of the method is Duration,
- In the first case, it returns the Duration that holds the value-added the given duration to this Duration.
- In the second case, it returns the Duration that holds the value-added the given amount in the unit to this Duration.
Example:
// Java program to demonstrate the example
// of plus() method of Duration
import java.time.*;
import java.time.temporal.*;
public class PlusOfDuration {
public static void main(String args[]) {
long amt = 10;
// Instantiates two Duration objects
Duration du1 = Duration.ofMinutes(3);
Duration du2 = Duration.parse("P2DT2H20M20S");
// Display du1, du2
System.out.println("du1: " + du1);
System.out.println("du2: " + du2);
System.out.println("amt to add: " + amt);
System.out.println();
// adds the given duration du1
// with this Duration du2 and returns
// the Duration i.e. here we are adding
// the given 3 minutes with this du2
// that holds the value of 2D:2H:20M:20S
Duration plus_val = du1.plus(du2);
// Display plus_val
System.out.println("du1.plus(du2): " + plus_val);
// adds the given amount in the given unit
// with this Duration and returns the Duration i.e.
// here we are adding the amt 10 in minutes unit
// with this du2 that holds the value of 2D:2H:20M:20S
plus_val = du2.plus(amt, ChronoUnit.MINUTES);
// Display plus_val
System.out.println("du2.plus(amt,ChronoUnit.MINUTES): " + plus_val);
}
}
Output
du1: PT3M
du2: PT50H20M20S
amt to add: 10
du1.plus(du2): PT50H23M20S
du2.plus(amt,ChronoUnit.MINUTES): PT50H30M20S