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
.
public Duration abs()
This method has no parameters.
This method returns a new Duration
object with an absolute length of duration.
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);}}
import java.time.Duration;
in line 1 is used to import the Duration
class.Example 1
, the abs()
method returns PT100H
for duration PT100H
as the sign is positive and no change of sign is needed.Example 2
, the abs()
method returns PT100H
for duration PT-100H
with the negative sign removed.