What is TimeUnit.toDays() in Java?

TimeUnit is an enumshort for enumeration that deals with different units of time and operations related to it.

This includes different units of time, such as:

  • NANOSECONDS
  • MICROSECONDS
  • MILLISECONDS
  • SECONDS
  • MINUTES
  • HOURS
  • DAYS

The toDays() method of TimeUnit is used to convert the time represented by the TimeUnit object to the number of days 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 toDays(long duration)

Parameters

  • long duration: the duration to be converted to the number of days.

The duration parameter value relies on the unit of time chosen for the time unit object.


Return value

The method returns the converted duration to the number of days, or 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 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 toDays method of the TimeUnit object created to get the time in the number of days.

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 number of days = " + time.toDays(currentTimeMilliseconds));
}
}