Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
subtractfrom
duration

What is Duration.subtractFrom() 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.

subtractFrom() is an instance method of the Duration class which is used to subtract the Duration object from the specified Temporal object.

The subtractFrom 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 subtractFrom(Temporal temporal)

Parameters

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

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.subtractFrom(currentLocalTime);
System.out.println("Original Temporal object - " + currentLocalTime);
System.out.println("Adjusted Temporal object - " + adjustedTemporalObject);
}
}
Implementation of the "subtractFrom" method

Explanation

Here is a line-by-line explanation of the above code:

  • 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 subtract the Duration object from the Temporal object using the subtractFrom() 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
subtractfrom
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