编程语言
首页 > 编程语言> > 有没有办法获得毫秒到天的转换而又不损失精度,也不需要用Java编写数学公式?

有没有办法获得毫秒到天的转换而又不损失精度,也不需要用Java编写数学公式?

作者:互联网

我使用TimeUnit.MILLISECONDS.toDays(ms)将毫秒时间量转换为天数,但阅读JavaDoc时发现它基于.convert()并失去精度

Convert the given time duration in the given unit to this unit. Conversions from finer to coarser granularities truncate, so lose precision. For example converting 999 milliseconds to seconds results in 0. Conversions from coarser to finer granularities with arguments that would numerically overflow saturate to Long.MIN_VALUE if negative or Long.MAX_VALUE if positive.

真的没想到,我的5分钟(300000ms)变成了0天.立即的解决方案是写这个

double days= (double)ms/1000*60*60*24;

这太糟糕了,我认为没有必要,但是可以.有什么建议吗?我还能使用其他功能吗?

ps:我不是在等你告诉我我应该将这些数字放入静态变量中,我试图了解哪种解决方案将是一个好的解决方案.提前致谢

解决方法:

只需以另一种方式使用TimeUnit:

double days = ms / (double) TimeUnit.DAYS.toMillis(1);

标签:date-conversion,timeunit,java,time
来源: https://codeday.me/bug/20191111/2020781.html