Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

tohours
java
communitycreator

What is TimeUnit.toHours() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

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

For example, it has different units of time like:

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

The toHours() method of the TimeUnit converts the time represented by the TimeUnit object to hours 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 toHours (long duration)

Parameters

  • long duration: the duration to be converted to hours.

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 hours 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 the `MILLISECONDS*, a time unit representing one-thousandth of a second.

We pass the current time in milliseconds to the toHours method of the TimeUnit object created to get the time in hours.

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

RELATED TAGS

tohours
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring