Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | subtractFrom() Method with Example
Duration Class subtractFrom() method: Here, we are going to learn about the subtractFrom() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 17, 2020
Duration Class subtractFrom() method
- subtractFrom() method is available in java.time package.
- subtractFrom() method is used to return the Temporal object subtracted this Duration from the given Temporal object.
- subtractFrom() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- subtractFrom() method may throw an exception at the time of performing subtraction.
- ArithmeticException: This exception may throw when the calculated results exceed the length of this Duration.
- DateTimeException: This exception may throw when the given object couldn't subtract this Duration.
Syntax:
public Temporal subtractFrom(Temporal temp);
Parameter(s):
- Temporal temp – represents the object by which to subtract this Duration.
Return value:
The return type of this method is Duration, it returns the Temporal that holds the value subtracted this Duration from the given Temporal object.
Example:
// Java program to demonstrate the example
// of subtractFrom(Temporal temp) method
// of Duration
import java.time.*;
import java.time.temporal.*;
public class SubtractFromDuration {
public static void main(String args[]) {
// Instantiates a Duration
// and LocalTime object
Duration du = Duration.ofHours(2);
LocalTime l_time = LocalTime.now();
// Display du and l_time
System.out.println("du to subtract: " + du);
System.out.println("l_time: " + l_time);
// subtracts this object (du) from the given
// object (l_time) i.e. we are subtracting
// duration (2 hrs) from l_time hours unit
l_time = (LocalTime) du.subtractFrom(l_time);
// Display updated l_time
System.out.println("du.subtractFrom(l_time): " + l_time);
}
}
Output
du to subtract: PT2H
l_time: 08:20:02.395444
du.subtractFrom(l_time): 06:20:02.395444