What is Duration.withNanos() in Java?
withNanos() is an instance method of the Duration. It returns a copy of the Duration object upon which this method is applied, along with the number of nanoseconds set to the passed value. The seconds part of the Duration object is retained without change.
The withNanos 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 Duration withNanos(int nanoOfSecond)
Parameters
long nanoOfSecond: The nanoseconds to represent. This value can be positive or negative.
Return value
This method returns a new Duration object.
Code
import java.time.Duration;public class Main {public static void main(String[] args) {Duration duration = Duration.ofSeconds(143234, 4223);int noOfNanosecondsToSet = 456;Duration newDuration = duration.withNanos(noOfNanosecondsToSet);System.out.printf("Original Duration Object - %s\nCloned Duration Object with different seconds value - %s", duration.toString().substring(2).replaceAll("(\\d[HMS])(?!$)", "$1 ").toLowerCase(), newDuration.toString().substring(2).replaceAll("(\\d[HMS])(?!$)", "$1 ").toLowerCase());}}
Explanation
- Line 1: We import the
Durationclass. - Line 6: We define a
Durationobject using theofSeconds()method. - Line 8: We define the number of nanoseconds’ value to be set in the new
Durationobject. - Line 10: We clone the object created in line 6 using the
withNanos()method. We do this by passing the new number of nanoseconds’ value defined in line 8. - Line 10: We print the base
Durationobject and the clonedDurationobject.