Stop converting time units the wrong way

Converting time units ilustration

Java programmers use many different approaches when converting time units. Some of those approaches are good, but most of them are just wrong and error prone. I am sure that most of you, at some point, found a code like this:

    long oneHourInSeconds = 60 * 60;

Let’s not lie, you have written it at some point. I know I have. The output of this code is correct and easy to understand. But imagine if you found something like this in the code:

    long days = (24 * (60 * 60)) * 2;

I know, the naming of this variable is terrible, but put that aside. Can you figure out what the programmer tried to calculate? Sure you can, but you will not know immediately what it represents. Let’s see a different approach but with the same naming.

    long days = TimeUnit.DAYS.toSeconds(2);

Now this is much better, right? Despite the terrible naming, we now know that this represents two days in seconds. This is much cleaner and less error-prone approach.

Start converting time units with TimeUnit class

Since Java 1.5 there is a class called TimeUnit, and it provides utility methods to convert across units. You can convert almost anything, days to seconds, seconds to nanoseconds, days to minutes and so on. By using TimeUnit anyone who maintains your code will be thankful and will not hate you that much.

These are some examples what you can do with it.

        long oneHourInSeconds = TimeUnit.HOURS.toSeconds(1);
        long oneMinuteInMilliseconds = TimeUnit.MINUTES.toMillis(1);
        long oneDayInSeconds = TimeUnit.DAYS.toSeconds(1);

You can check the API documentation to see what else you can do with it. Also, TimeUnit is an enum and you should check the source code because it is a great example of how you can use enums.

Start doing the right thing

I hope that this blog post helps you understand the importance of writing a simple and clean code. I know that a thing like this looks trivial, but it can all go sideways very fast. Someone can change your code only because he or she misunderstood what you are doing. And please, do not ever name your variable “days” or anything like that. There is a great quote from Martin Flower which you should always keep in mind while writing software.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Thanks to oFca for proofreading this blog post.