Unknown Java Features Part 2: TimeUnit

Simple Way to use different time units

TimeUnit is the simplest way to work with different time units since Java 5.

Aren’t you annoyed about writing all the time how to convert e.g. minutes to milliseconds? Like “5 * 60 * 1000”?

Sure it’s no rocket science, but it’s difficult to read. The next step is often to extract it as a constant. Then you at least know immediately that’s 15 minutes.

But there is an easier way to express the same thing. The TimeUnit enum. So let’s seeĀ it in action.

 

With TimeUnit you just express the unit directly and you can still extract it to a constant if needed.

Wanna go to sleep, wait or join?

There are shortcut functions for those as well:

 

TL:TR

TimeUnit is an easy way to convert between time units and express it more clearly. Shortcuts methods like sleep round things up.

This entry was posted in common practice, Java, Unknown feature and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *