Search code examples
javaconverterslong-integerbigdecimalduration

Convert time duration (BigDecimal value + time units) to milliseconds long


I have to create a function that has 2 input parameters: Time duration in BigDecimal (precision 38, scale 6) and TimeUnitsType enum (DAYS, HOURS, MINUTES or SECONDS).

And I need to get long value (milliseconds) as a result; As I understand, the longValue() method from BigDecimal won't work precisely here as it set scale to 0, and longValueExact() will throw ArithmeticException("Overflow") (because precision - scale > 19)

public static long convertTimeToMillis(BigDecimal time, TimeUnitsType timeUnitsType) {
    long timeLong = time.longValue();
    switch (timeUnitsType) {
        case DAYS:
            return TimeUnit.DAYS.toMillis(timeLong);
        case HOURS:
            return TimeUnit.HOURS.toMillis(timeLong);
        case MINUTES:
            return TimeUnit.MINUTES.toMillis(timeLong);
        default:
            return TimeUnit.SECONDS.toMillis(timeLong);
    }
}

So I need to make individual calculation for each case separately. Can you please help me? BigDecimal operations scares me a little, because I haven't work with them before :) And the precision is required in the rest of the task.

P.S. Java version is 1.6


Solution

  • If time is in the unit of timeUnitsType and you are converting that time (in its units) to milliseconds then there is always the chance of an overflow. long simply cannot hold more than 19 digits, while here you could have 32 digits 6 decimal places in seconds and converting that to milliseconds would make it up to 35 digits. 32 digit days to milliseconds is even worse...

    Are you sure you need to convert this BigDecimal in its TimeUnit to a single long in milliseconds?

    BigDecimal.longValueExact() will throw an exception if there would be any information lost. So if you check for that exception and handle it then I guess things will be ok.