sarbuLopex sarbuLopex -4 years ago 74
Java Question

Is there a way to obtain a milliseconds to days conversion without losing precision and without the need to write the mathematical formula in Java?

I was using TimeUnit.MILLISECONDS.toDays(ms) to convert a millisecond time quantity to days but reading the JavaDoc I noticed it's based on

.convert()
and loses precision


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.


It was really not expected, my 5 minutes (300000ms) became 0 days. The immediate solution was to write this

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


It's awful and I think unnecessary, but it works. Any advice? Any other functions I can use?

ps: I'm not waiting you to tell me I should put those numbers into static vars, I'm trying to understand what kind of solution would be a good solution. Thanks in advance

Answer Source

Just use TimeUnit the other way round:

double days = ms / (double) TimeUnit.DAYS.toMillis(1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download