TimeUnit toNanos() method in Java with Examples

The toNanos() method of TimeUnit Class is used to get the time represented by the TimeUnit object, as the number of NanoSeconds, since midnight UTC on the 1st January 1970.

Syntax:

public long toNanos(long duration)

Parameters: This method accepts a mandatory parameter duration which is the duration in milliSeconds.



Return Value: This method returns the converted duration as NanoSeconds.

Below programt illustrate the implementation of TimeUnit toNanos() method:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// toNanos() method of TimeUnit Class
  
import java.util.concurrent.*;
import java.util.Date;
  
class GFG {
    public static void main(String args[])
    {
        // Get current time in milliseconds
        long timeInMilliSec = new Date().getTime();
  
        // Create a TimeUnit object
        TimeUnit time = TimeUnit.MILLISECONDS;
  
        // Convert milliseconds to NanoSeconds
        // using toNanos() method
        System.out.println("Time " + timeInMilliSec
                           + " milliSeconds in NanoSeconds = "
                           + time.toNanos(timeInMilliSec));
    }
}

chevron_right


Output:

Time 1539585501608 milliSeconds in NanoSeconds = 1539585501608000000

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// toNanos() method of TimeUnit Class
  
import java.util.concurrent.*;
import java.util.Calendar;
  
class GFG {
    public static void main(String args[])
    {
        // Get current time in milliseconds
        long timeInMilliSec = Calendar
                                  .getInstance()
                                  .getTimeInMillis();
  
        // Create a TimeUnit object
        TimeUnit time = TimeUnit.MILLISECONDS;
  
        // Convert milliseconds to NanoSeconds
        // using toNanos() method
        System.out.println("Time " + timeInMilliSec
                           + " milliSeconds in NanoSeconds = "
                           + time.toNanos(timeInMilliSec));
    }
}

chevron_right


Output:

Time 1539585503771 milliSeconds in NanoSeconds = 1539585503771000000


My Personal Notes arrow_drop_up

Technical Content Engineer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.