Duration subtractFrom(Temporal) method in Java with Examples
The subtractFrom(Temporal) method of Duration Class in java.time package is used subtract this duration to the specified temporal object, passed as the parameter.
Syntax:
public Temporal subtractFrom?(Temporal temporalObject)
Parameters: This method accepts a parameter temporalObject which is the amount to be adjusted in this duration. It should not be null.
Return Value: This method returns an object of the same type with the temporalObject adjusted to it.
Exception: This method throws:
- DateTimeException: if unable to subtract.
- ArithmeticException: if numeric overflow occurs.
Below examples illustrate the Duration.subtractFrom() method:
Example 1:
import java.time.*;
public class GFG {
public static void main(String[] args)
{
Duration duration1
= Duration.parse( "P2DT3H4M" );
LocalDateTime currentTime
= LocalDateTime.now();
System.out.println( "Original time: "
+ currentTime);
System.out.println(
duration1
.subtractFrom(currentTime));
}
}
|
Output:
Original time: 2018-11-26T06:48:30.256
2018-11-24T03:44:30.256
Example 2:
import java.time.*;
public class GFG {
public static void main(String[] args)
{
Duration duration2
= Duration.ofDays(- 5 );
LocalDateTime currentTime
= LocalDateTime.now();
System.out.println( "Original time: "
+ currentTime);
System.out.println(
duration2
.subtractFrom(currentTime));
}
}
|
Output:
Original time: 2018-11-26T06:48:33.319
2018-12-01T06:48:33.319
Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#subtractFrom-java.time.temporal.Temporal-
Last Updated :
26 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...