What is TimeUnit.toMillis in Java?
Overview
TimeUnit is an
For example, it has different units of time like:
NANOSECONDSMICROSECONDSMILLISECONDSSECONDSMINUTESHOURSDAYS
The toMillis() method of the TimeUnit converts the time represented by the TimeUnit object to milliseconds since midnight UTC on January 1, 1970.
How to import the TimeUnit enum
The TimeUnit enum is defined in the java.util.concurrent package. Use the import statement below to import the TimeUnit enum.
import java.util.concurrent.TimeUnit;
Syntax
public long toMillis(long duration)
Parameters
long duration: the duration to be converted to milliseconds.
The duration parameter value relies on the unit of time chosen for the time unit object.
Return value
This method returns the converted duration to milliseconds, Long.MIN_VALUE if the conversion overflows negatively, or Long.MAX_VALUE if it overflows positively.
Code
In the code below, we get the current time in seconds using the Instant class.
Next, we create a TimeUnit object with the help of SECONDS, the time unit represents one second.
We pass the current time in seconds to the toMillis method of the TimeUnit object created to get the time in milliseconds.
import java.time.Instant;import java.util.concurrent.TimeUnit;class Main {public static void main(String[] args) {long currentTimeSeconds = Instant.now().getEpochSecond();TimeUnit timeUnit = TimeUnit.SECONDS;System.out.println("The time " + currentTimeSeconds + " seconds in milliseconds = " + timeUnit.toMillis(currentTimeSeconds));}}