What is the Duration.abs() method in Java?
The abs() method is an instance method of the Duration class which returns a positive copy of any negative duration. For example, PT-1H will be returned as PT1H.
Syntax
public Duration abs()
Parameters
This method has no parameters.
Return value
This method returns a new Duration object with an absolute length of duration.
Code
The widget below shows the abs() method being used.
import java.time.Duration;public class Main{public static void main(String[] args) {// Example 1Duration duration = Duration.ofHours(100);Duration absDuration = duration.abs();System.out.printf("Original duration - %s; Absolute Duration - %s", duration, absDuration);System.out.println();// Example 2duration = Duration.ofHours(-100);absDuration = duration.abs();System.out.printf("Original duration - %s; Absolute Duration - %s", duration, absDuration);}}
Explanation
import java.time.Duration;in line 1 is used to import theDurationclass.- In
Example 1, theabs()method returnsPT100Hfor durationPT100Has the sign is positive and no change of sign is needed. - In
Example 2, theabs()method returnsPT100Hfor durationPT-100Hwith the negative sign removed.