java.time.Duration.withNanos() Method Example



Description

The java.time.Duration.withNanos(int nanoOfSecond) method returns a copy of this duration with the specified nanoOfsecond.

Declaration

Following is the declaration for java.time.Duration.withNanos(int nanoOfSecond) method.

public Duration withNanos(int nanoOfSecond)

Parameters

nanoOfSecond − the nanoOfsecond to represent, from 0 to 999,999,999.

Return Value

a Duration based on this period with the requested nanoseconds, not null

Exception

DateTimeException − if the nanoOfsecond is invalid.

Example

The following example shows the usage of java.time.Duration.withNanos(int nanoOfSecond) method.

package com.tutorialspoint;

import java.time.Duration;

public class DurationDemo {
   public static void main(String[] args) {

      Duration duration = Duration.ofDays(2);
      System.out.println(duration.toString());  
      duration = duration.withNanos(2000);
      System.out.println(duration.toString());  
   }
}

Let us compile and run the above program, this will produce the following result −

PT48H
PT48H0.000002S
Advertisements