Java Duration Class | addTo() Method with Example

Duration Class addTo() method: Here, we are going to learn about the addTo() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 14, 2020

Duration Class addTo() method

  • addTo() method is available in java.time package.
  • addTo() method is used to add this Duration object into the given Temporal object and returns a Temporal.
  • addTo() 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.
  • addTo() method may throw an exception at the time of adding an object.
    • DateTimeException: This exception may throw when this object can't add to the given object.
    • ArithmeticException: This exception may throw when the calculated result limit exceeds.

Syntax:

    public Temporal addTo(Temporal temp);

Parameter(s):

  • Temporal temp – represents the Temporal object to add to fit in this Duration.

Return value:

The return type of this method is Temporal, it returns the Temporal added this object in to the given object.

Example:

// Java program to demonstrate the example 
// of Temporal addTo(Temporal temp) method of Duration

import java.time.*;
import java.time.temporal.*;

public class AddToOfDuration {
    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: " + du);
        System.out.println("l_time: " + l_time);

        // adds this object (du) into the 
        // given object (l_time) i.e. we are adding
        // duration (2 hrs) in l_time hours unit
        l_time = (LocalTime) du.addTo(l_time);

        // Display updated l_time
        System.out.println("du.addTo(l_time): " + l_time);
    }
}

Output

du: PT2H
l_time: 17:05:28.886833
du.addTo(l_time): 19:05:28.886833


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.