Java: Converting Time from one format to another

I’ve started using Checkstyle on my code base. One of the checks I’ve enabled is magicnumbers, which as its name implies, ensures your code isn’t using magic numbers.

As a result, I found some code that was doing the following:

How many times have you done that? Or wanted to convert milliseconds to minutes or various others? Created a constant with 60*60*24 for conversions?

Doing a bit of Googling, I learned that in Java 6, as part of the Concurrency updates, the JDK now has a TimeUnit class. This then allows one to do the following instead:

That’s much cleaner, and less prone to both misunderstanding and errors.

  • Checkstyle:[elink link=””]
  • TimeUnit: [elink link=””]