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 1
Duration duration = Duration.ofHours(100);
Duration absDuration = duration.abs();
System.out.printf("Original duration - %s; Absolute Duration - %s", duration, absDuration);
System.out.println();
// Example 2
duration = 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 the Duration class.
  • In Example 1, the abs() method returns PT100H for duration PT100H as the sign is positive and no change of sign is needed.
  • In Example 2, the abs() method returns PT100H for duration PT-100H with the negative sign removed.