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.


    public Temporal subtractFrom(Temporal temp);


  • 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.


// 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 =;

        // 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);


du to subtract: PT2H
l_time: 08:20:02.395444
du.subtractFrom(l_time): 06:20:02.395444

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.