What is Duration.subtractFrom() in Java?

subtractFrom() is an instance method of the Duration class which is used to subtract the Duration object from the specified Temporal object.

The subtractFrom 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 Temporal subtractFrom(Temporal temporal)

Parameters

  • Temporal temporal: The Temporal object that represents the amount to be modified/adjusted.

Return value

This method returns the adjusted Temporal object.

Code

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.Temporal;
public class Main {
public static void main(String[] args) {
Duration duration = Duration.ofSeconds(143234, 4223);
LocalDateTime currentLocalTime = LocalDateTime.now();
Temporal adjustedTemporalObject = duration.subtractFrom(currentLocalTime);
System.out.println("Original Temporal object - " + currentLocalTime);
System.out.println("Adjusted Temporal object - " + adjustedTemporalObject);
}
}

Explanation

Here is a line-by-line explanation of the above code:

  • Lines 1-3: We import the relevant packages.
  • Line 8: We define a Duration object using the ofSeconds() method.
  • Line 10: We get the Temporal object to adjust to. The LocalDateTime class implements the Temporal interface.
  • Line 12: We subtract the Duration object from the Temporal object using the subtractFrom() method.
  • Line 14: We print the original Temporal object defined in line 10.
  • Line 16: We print the adjusted Temporal object obtained in line 12.

Free Resources