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: TheTemporalobject 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
Durationobject using theofSeconds()method. - Line 10: We get the
Temporalobject to adjust to. TheLocalDateTimeclass implements theTemporalinterface. - Line 12: We subtract the
Durationobject from theTemporalobject using thesubtractFrom()method. - Line 14: We print the original
Temporalobject defined in line 10. - Line 16: We print the adjusted
Temporalobject obtained in line 12.