7

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

sarbuLopex
  • 1,777
  • 1
  • 15
  • 22

1 Answers1

4

Just use TimeUnit the other way round:

double days = ms / (double) TimeUnit.DAYS.toMillis(1);
Markus Benko
  • 1,507
  • 8
  • 8
  • I think this closes the issue, thank you! This kind of response is what StackOverflow is made for – sarbuLopex Mar 23 '17 at 11:10
  • @sarbuLopex And I hope you know the limitation of the answer, namely to count every day as equivalent to 24 hours (which is not true, see daylight saving changes in various time zones). – Meno Hochschild Mar 23 '17 at 13:26
  • 1
    The answer is not more and not less than what has been asked for. API docs for TimeUnit say *a day is defined as twenty four hours* and as TimeUnit is used in this solution it should be clear what that line of code does. Without having more information about the context in which the converted value is used, we barely can judge if it is correct to live with that (wrong) 24h assumption or not. – Markus Benko Mar 23 '17 at 14:07
  • @MenoHochschild I'm lucky enough it'll only be used with finite amount of time in my case, not related to calendar problems or time zones. However thanks for the advice, if you can write a better answer It would be much appreciated – sarbuLopex Mar 23 '17 at 14:12