Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
addto
duration

What is Duration.addTo() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

addTo() is an instance method of Duration and is used to add a Duration object to a specified Temporal object.

The addTo method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class, check the following import statement.

import java.time.Duration;

Syntax


public Temporal addTo(Temporal temporal)

Parameters

  • Temporal temporal: The Temporal object that represents the amount to be modified/adjusted in the Duration object.

Return value

This method returns the adjusted Temporal object.

Code

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.Temporal;
public class Main {
public static void main(String[] args) {
Duration duration = Duration.ofSeconds(143234, 4223);
LocalDateTime currentLocalTime = LocalDateTime.now();
Temporal adjustedTemporalObject = duration.addTo(currentLocalTime);
System.out.println("Original Temporal object - " + currentLocalTime);
System.out.println("Adjusted Temporal object - " + adjustedTemporalObject);
}
}
Implementation of the "addTo()" method

Explanation

  • Lines 1-3: We import the relevant packages.
  • Line 8: We define a Duration object using the ofSeconds() method.
  • Line 10: We get the Temporal object to adjust to. The LocalDateTime class implements the Temporal interface.
  • Line 12: We add the Temporal object to the Duration object using the addTo() method.
  • Line 14: We print the original Temporal object defined in line 10.
  • Line 16: We print the adjusted Temporal object obtained in line 12.

RELATED TAGS

java
communitycreator
addto
duration

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring