将持续时间(BigDecimal 值 + 时间单位)转换为毫秒长

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

我必须创建一个具有 2 个输入参数的函数: Time duration BigDecimal(精度 38,小数位数 6) 和 TimeUnitsType enum(天、小时、分钟或秒)。

我需要得到 long 值(毫秒)作为结果; 据我了解,BigDecimal 中的 longValue() 方法不会在这里精确工作,因为它将比例设置为 0,而 longValueExact() 将抛出 ArithmeticException("Overflow") (因为精度 - 比例 > 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);
    }
}

所以我需要针对每个案例单独计算。你能帮我么? BigDecimal 操作让我有点害怕,因为我以前没有使用过它们:) 其余任务需要精度。

P.S。 Java 版本为 1.6

如果 timetimeUnitsType 为单位,并且您正在将该时间(以其单位)转换为毫秒,那么总会有溢出的机会。 long 不能容纳超过 19 位数字,而在这里你可以有 32 位数字,小数点后 6 位以秒为单位,将其转换为毫秒将使其达到 35 位数字。 32 位天到毫秒更糟...

您确定需要将 BigDecimal 中的 TimeUnit 转换为单个 long 毫秒吗?

如果有任何信息丢失,

BigDecimal.longValueExact() 将抛出异常。因此,如果您检查并处理该异常,那么我想一切都会好起来的。

输入值中最多允许 6 位小数是有原因的,因此您不能忽略它们。自己进行转换,创建一个保留小数位的新 BigDecimal。一旦你有毫秒,四舍五入那个 BigDecimal。最后,将 BigDecimal 与 Long.MAX_VALUE 和 MIN_VALUE 进行比较。如果超出这些范围,则抛出异常。