TimeUnit is an
For example, it has different units of time like:
NANOSECONDSMICROSECONDSMILLISECONDSSECONDSMINUTESHOURSDAYSThe toMillis() method of the TimeUnit converts the time represented by the TimeUnit object to milliseconds since midnight UTC on January 1, 1970.
TimeUnit enumThe 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;
public long toMillis(long duration)
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.
This method returns the converted duration to milliseconds, Long.MIN_VALUE if the conversion overflows negatively, or Long.MAX_VALUE if it overflows positively.
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));}}