Duration addTo(Temporal) method in Java with Examples

The addTo(Temporal) method of Duration Class in java.time package is used add this duration to the specified temporal object, passed as the parameter. Syntax:
public Temporal addTo?(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 add.
- ArithmeticException: if numeric overflow occurs.
Below examples illustrate the Duration.addTo() method: Example 1:Â
Java
// Java code to illustrate Duration addTo() methodÂ
import java.time.*;Â
public class GFG {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // Duration 1 using parse() method        Duration duration1            = Duration.parse("P2DT3H4M");Â
        // Get the time to be adjusted        LocalDateTime currentTime            = LocalDateTime.now();Â
        System.out.println("Original time: "                           + currentTime);Â
        // Adjust the time        // using addTo() method        System.out.println(            duration1                .addTo(currentTime));    }} |
Output:
Original time: 2018-11-26T07:01:13.535 2018-11-28T10:05:13.535
Example 2:Â
Java
// Java code to illustrate duration addTo() methodÂ
import java.time.*;Â
public class GFG {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // Duration        Duration duration2            = Duration.ofDays(-5);Â
        // Get the time to be adjusted        LocalDateTime currentTime            = LocalDateTime.now();Â
        System.out.println("Original time: "                           + currentTime);Â
        // Adjust the time        // using addTo() method        System.out.println(            duration2                .addTo(currentTime));    }} |
Output:
Original time: 2018-11-26T07:01:16.615 2018-11-21T07:01:16.615
Reference: Oracle Doc



