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
int days = (int) (milliseconds / (1000*60*60*24)); If you have weeks too: int days = (int) ((milliseconds / (1000*60*60*24)) % 7); int weeks = (int) (milliseconds / (1000*60*60*24*7));
toMinutes(millis) - (hours * 60); long seconds = TimeUnit. MILLISECONDS. toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60)); Use String.
Save this answer. Show activity on this post. long seconds = timeInMilliSeconds / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = hours / 24; String time = days + ":" + hours % 24 + ":" + minutes % 60 + ":" + seconds % 60; Save this answer.
Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).
Just use TimeUnit the other way round:
double days = ms / (double) TimeUnit.DAYS.toMillis(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With