What is TimeUnit.toMinutes() in Java?

TimeUnit is an enum that deals with different units of time and operations related to it. For example, TimeUnit has different units of time like NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, and DAYS.

The toMinutes() method of the TimeUnit class is used to convert the time represented by the TimeUnit object to minutes of Unix timeThe time since midnight, January 1, 1970, UTC time.

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 toMinutes(long duration)

Parameters

  • duration: the duration (generally in milliseconds) to be converted to minutes.

Return value

The method returns the converted duration to minutes. The method returns Long.MIN_VALUE if the conversion overflows negatively, and Long.MAX_VALUE if it overflows positively.

Code

In the code below, we use the Calendar class to get the current time in milliseconds.

Next, we create a TimeUnit object with the help of MILLISECONDS, which is a time unit that represents one-thousandth of a second.

We pass the current time in milliseconds to the toMinutes method of the TimeUnit object to get the time in minutes.

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 minutes = " + time.toMinutes(currentTimeMilliseconds));
}
}

Free Resources