Duration withNanos() method in Java


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));

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements