Open In App

Duration withNanos(long) method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The withNanos(long) method of Duration Class in java.time package is used to get an immutable copy of this duration with the specified amount of nano-seconds passed as the parameter.

Syntax:

public Duration withNanos(long amountOfNanos)

Parameters: This method accepts a parameter amountOfNanos which is the amount of nano-seconds.

Return Value: This method returns a Duration of the nano-seconds passed as the parameter.

Exception: This method throws DateTimeException if the nano-of-second is invalid.

Below examples illustrate the Duration.withNanos() method:

Example 1:




// Java code to illustrate withNanos() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the amount of nano-seconds
        int amountOfNanos = 30000;
  
        // Duration using parse() method
        Duration duration
            = Duration.parse("P2DT3H4M");
  
        // Get the duration in nano-seconds
        // using withNanos() method
        System.out.println(duration
                               .withNanos(amountOfNanos));
    }
}


Output:

PT51H4M0.00003S

Example 2:




// Java code to illustrate withNanos() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the amount of nano-seconds
        int amountOfNanos = 100000;
  
        // Duration using ofHours() method
        Duration duration = Duration.ofHours(5);
  
        // Get the duration in nano-seconds
        // using withNanos() method
        System.out.println(duration
                               .withNanos(amountOfNanos));
    }
}


Output:

PT5H0.0001S

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#withNanos-int-



Last Updated : 26 Nov, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads