Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | plusDays() Method with Example
Duration Class plusDays() method: Here, we are going to learn about the plusDays() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 16, 2020
Duration Class plusDays() method
- plusDays() method is available in java.time package.
- plusDays() method is used to add the given duration in days to this Duration and return the Duration.
- plusDays() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- plusDays() method may throw an exception at the time of performing addition.
ArithmeticException: This exception may throw when the calculated results exceed the length of this Duration.
Syntax:
public Duration plusDays(long day_val);
Parameter(s):
- long day_val – represents the day value to add to this Duration.
Return value:
The return type of this method is Duration, it returns the Duration that holds the value added the given days to this Duration.
Example:
// Java program to demonstrate the example
// of plusDays(long day_val) method of Duration
import java.time.*;
public class PlusDaysOfDuration {
public static void main(String args[]) {
long days = 2;
// Instantiates two Duration objects
Duration du1 = Duration.ofDays(3);
Duration du2 = Duration.parse("P2DT20M");
// Display du1, du2
System.out.println("du1: " + du1);
System.out.println("du2: " + du2);
System.out.println("days to add: " + days);
System.out.println();
// adds the given duration in days with this
// Duration du1 and returns the Duration
// i.e. here we are adding the given 2 days
// with this du1 that holds the value of 3 days
// i.e.( 72 hrs + 48 hrs = 120 hrs )
Duration plus_val = du1.plusDays(days);
// Display plus_val
System.out.println("du1.plusDays(days): " + plus_val);
// adds the given duration in days with this
// Duration du2 and returns the Duration
// i.e. here we are adding the given 2 days
// with this du2 that holds the value of 2D:20M
// i.e.( 48 hrs + 48 hrs = 96 hrs )
plus_val = du2.plusDays(days);
// Display plus_val
System.out.println("du2.plusDays(days): " + plus_val);
}
}
Output
du1: PT72H
du2: PT48H20M
days to add: 2
du1.plusDays(days): PT120H
du2.plusDays(days): PT96H20M