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 code to illustrate 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)); } } |
Original time: 2018-11-26T07:01:13.535 2018-11-28T10:05:13.535
Example 2:
// Java code to illustrate 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)); } } |
Original time: 2018-11-26T07:01:16.615 2018-11-21T07:01:16.615
Reference: Oracle Doc
Recommended Posts:
- Duration dividedBy(Duration) method in Java with Examples
- Duration equals(Duration) method in Java with Examples
- Duration minus(Duration) method in Java with Examples
- Duration compareTo(Duration) method in Java with Examples
- Duration plus(Duration) method in Java with Examples
- Duration abs() method in Java with Examples
- Duration toMillisPart() method in Java with Examples
- Duration toNanosPart() method in Java with Examples
- Duration toSecondsPart() method in Java with Examples
- Duration from(TemporalUnit) method in Java with Examples
- Duration toSeconds() method in Java with Examples
- Duration toDaysPart() method in Java with Examples
- Duration toMinutes() method in Java with Examples
- Duration toHours() method in Java with Examples
- Duration hashCode() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



