TimeUnit
is an
It has different units of time such as:
NANOSECONDS
MICROSECONDS
MILLISECONDS
SECONDS
MINUTES
HOURS
DAYS
The toMicros()
method of the TimeUnit
converts the time represented by the TimeUnit object to microseconds 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 toMicros(long duration)
long duration
: the duration to be converted to nanoseconds.The duration parameter value relies on the unit of time chosen for the time unit object.
The method returns the converted duration to nanoseconds.
Long.MIN_VALUE
if the conversion overflows negatively.Long.MAX_VALUE
if it overflows positively.In the code below, we get the current time in milliseconds using the Calendar
class.
Next, we create a TimeUnit
object with the help of MILLISECONDS
, a time unit that represents one-thousandth of a second.
We pass the current time in milliseconds to the TimeUnit
object’s toMicros
method to get the time in microseconds.
import java.util.Calendar;import java.util.concurrent.TimeUnit;class Main {public static void main(String[] args) {Calendar calendar = Calendar.getInstance();long currentTimeMilliseconds = calendar.getTimeInMillis();TimeUnit time = TimeUnit.MILLISECONDS;System.out.println("The time " + currentTimeMilliseconds + " milliSeconds in Microseconds = " + time.toMicros(currentTimeMilliseconds));}}