TimeUnit Class in Java with Examples
The TimeUnit
class in Java is a part of the java.util.concurrent
package and provides a set of useful methods to perform time-based operations. It is an enum that represents time units at a given granularity and provides conversion methods between them.
Here are some examples of how to use the TimeUnit
class in Java:
- Converting time units:
long minutes = TimeUnit.HOURS.toMinutes(2); // Converts 2 hours to minutes
long seconds = TimeUnit.MINUTES.toSeconds(30); // Converts 30 minutes to seconds
- Delaying execution:
try {
TimeUnit.SECONDS.sleep(5); // Delays execution for 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
- Measuring elapsed time:
long startTime = System.nanoTime();
// Code to be measured
long endTime = System.nanoTime();
long elapsedTimeInMilliseconds = TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS);
- Setting timeouts:
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.awaitTermination(10, TimeUnit.SECONDS); // Waits for 10 seconds for the task to complete
} catch (InterruptedException e) {
e.printStackTrace();
}
- Formatting time:
long durationInSeconds = 120;
String formattedDuration = String.format("%d min, %d sec",
TimeUnit.SECONDS.toMinutes(durationInSeconds),
durationInSeconds - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(durationInSeconds))
);
System.out.println(formattedDuration); // Outputs "2 min, 0 sec"
These are just a few examples of how to use the TimeUnit
class in Java. It provides a lot of flexibility when dealing with time-based operations and can be very useful in multi-threaded applications.