Duration withNanos() method in Java

Java 8ProgrammingObject Oriented Programming

The immutable copy of a duration with the required nanoseconds is obtained using the method withNanos() in the Duration class in Java. This method requires a single parameter i.e. the number of nanoseconds and it returns the duration with the required nanoseconds that were passed as a parameter.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.Duration;
public class Demo {
   public static void main(String[] args) {
      int nanoseconds = 1000000;
      Duration duration = Duration.ofHours(10);
      System.out.println("The duration is: " + duration.withNanos(nanoseconds));
   }
}

Output

The duration is: PT10H0.001S

Now let us understand the above program.

The immutable copy of the duration with the required nanoseconds is obtained using the method withNanos() and then it is printed. A code snippet that demonstrates this is as follows −

int nanoseconds = 1000000;
Duration duration = Duration.ofHours(10);
System.out.println("The duration is: " + duration.withNanos(nanoseconds));
raja
Published on 13-Mar-2019 12:41:33
Advertisements