The TimeUnit enum is part of the java.util.concurrent package and provides a set of time units, ranging from nanoseconds to days, which is commonly used for managing time durations and conversions in concurrent and time-sensitive applications. In this article, we will see how to convert nano seconds to seconds using the TimeUnit enum.

Convert Nanoseconds to Seconds:

To convert time durations from one unit to another using the TimeUnit enum, we can use the convert() method. In this example, we are converting nanoseconds to seconds.

import java.util.concurrent.TimeUnit;

public class NanosecondsToSecondsExample {

    public static void main(String[] args) {
        // Define the time duration in nanoseconds
        long nanoseconds = 1000000000; // 1 second in nanoseconds
        
        // Convert nanoseconds to seconds using TimeUnit
        long seconds = TimeUnit.SECONDS.convert(nanoseconds, TimeUnit.NANOSECONDS);
        
        // Display the result
        System.out.println("Nanoseconds: " + nanoseconds);
        System.out.println("Seconds: " + seconds);
    }
}

In the above example, we define time duration in nanoseconds (1 second is equal to 1,000,000,000 nanoseconds). We then use the TimeUnit.SECONDS.convert() method to convert the given nanoseconds to seconds. Finally, using the System.out.println() method we displayed the result.

References:

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html

Categorized in:

Tagged in: