Java: Converting Time from one format to another

2013-11-21

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:

1
final double minutes = timeInSeconds / 60;
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:
1
2
final double minutes = TimeUnit.SECONDS.toMinutes(timeInSeconds);
final double hours = TimeUnit.MILLISECONDS.toHours(timeInMillis);

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


Comments: