toNanos()
is an instance method of the Duration
class used to convert the duration to the total length in nanoseconds (expressed as a long
).
The toNanos()
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;
public long toNanos()
The method has no parameters.
This method returns the total length of the duration in nanoseconds.
In the code below, Duration
class objects of different time units are converted to nanoseconds.
import java.time.Duration;public class Main{public static void main(String[] args) {Duration durationInMilliSeconds = Duration.ofMillis(10000);System.out.println("100 milliseconds in Nanoseconds - " + durationInMilliSeconds.toNanos());Duration durationInMinutes = Duration.ofMinutes(10);System.out.println("10 minutes in Nanoseconds - " + durationInMinutes.toNanos());}}