Search code examples
javatimeunit

Double Timeunit Conversion


TimeUnit.toSeconds works well when the result is > 1. However, because we're dealing with longs, if the result is between 0 and 1 exclusive, we get 0 instead. Is the a java SDK function that handles double conversions for us?

I understand that I can perform these conversion myself by multiplying or dividing by the appropriate double. However, it is error prone and does not read well. My preference is to use an existing function from the Java SDK, similar to Java's TimeUnit.

Minimal example demonstrating my situation:

import java.util.*;
import java.util.concurrent.*;
public class Main {
    public static void main(String[] args) {
        System.out.println(TimeUnit.MILLISECONDS.toSeconds(1));
    }
}

Output:

0

I want a function that handles doubles that returns 0.001


Solution

  • korolar’s suggestion is so good it deserves to be an answer and have proper formatting. It gives you approximately half of what you want. If you’re to do the multiplication or division yourself, you can at least take the number to multiply or divide by from the library enum.

    public static double millisToSeconds(long millis) {
        return (double) millis / TimeUnit.SECONDS.toMillis(1);
    }
    

    Now millisToSeconds(1) gives 0.001. I agree with the comments by JB Nizet and VGR that you should wrap the calculation in a method with a nice name to keep your code well readable. If you want the method to be more general:

    public static double convertTimeUnit(double amount, TimeUnit from, TimeUnit to) {
        // is from or to the larger unit?
        if (from.ordinal() < to.ordinal()) { // from is smaller
            return amount / from.convert(1, to);
        } else {
            return amount * to.convert(1, from);
        }
    }
    

    Now convertTimeUnit(1, TimeUnit.MILLISECONDS, TimeUnit.SECONDS) gives 0.001 as before, while convertTimeUnit(1, TimeUnit.SECONDS, TimeUnit.MILLISECONDS) gives 1000.0.