What is Duration.negated() in Java?

negated() is an instance method of the Duration class which is used to swap the sign of the total length of the duration object. Hence, this method returns a copy of the Duration object with the length of the duration negated.

The negated method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class check the following import statement.

import java.time.Duration;

Syntax


public Duration negated()

Parameters

This method has no parameters.

Return value

This method returns a new Duration object with the length of the Duration negated.

Code

import java.time.Duration;
public class Main{
public static void main(String[] args) {
// Example 1
Duration duration = Duration.ofHours(100);
Duration negatedDuration = duration.negated();
System.out.printf("Original duration - %s; Negated Duration - %s", duration, negatedDuration);
System.out.println();
// Example 2
duration = Duration.ofHours(-100);
negatedDuration = duration.negated();
System.out.printf("Original duration - %s; Negated Duration - %s", duration, negatedDuration);
}
}

Example 1

  • duration - PT100H

The method returns PT-100H with the sign changed from positive to negative.

Example 2

  • duration - PT-100H

The method returns PT100H with the sign changed from negative to positive.