Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | abs() Method with Example
Duration Class abs() method: Here, we are going to learn about the abs() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 14, 2020
Duration Class abs() method
- abs() method is available in java.time package.
- abs() method is used to clone this Duration but available with positive duration value instead of a negative duration.
- abs() 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.
- abs() method may throw an exception at the time of returning the absolute value of this Duration.
ArithmeticException: This exception may throw when the calculated result exceeds.
Syntax:
public Duration abs();
Parameter(s):
Return value:
The return type of this method is Duration, it returns this Duration but available with positive absolute duration values.
Example:
// Java program to demonstrate the example
// of Duration abs() method of Duration
import java.time.*;
import java.time.temporal.*;
public class AbsOfDuration {
public static void main(String args[]) {
// Instantiates two Duration objects
Duration du1 = Duration.between(LocalTime.MAX, LocalTime.MIN);
Duration du2 = Duration.ofHours(-2);
// Here, we are representing absolute
// values of du1 and du2 by using abs() method
Duration du1_abs = du1.abs();
Duration du2_abs = du2.abs();
// gets the value of the given unit for
// du1 and du1_abs
long du1_sec = du1.get(ChronoUnit.SECONDS);
long du1_sec_abs = du1_abs.get(ChronoUnit.SECONDS);
// Display du1 and du1_abs
System.out.println("du1: " + du1_sec);
System.out.println("du1.abs(): " + du1_sec_abs);
System.out.println();
// Display du2 and du2_abs
System.out.println("du2: " + du2);
System.out.println("du2.abs(): " + du2_abs);
}
}
Output
du1: -86400
du1.abs(): 86399
du2: PT-2H
du2.abs(): PT2H