Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 282
sarbuLopex Avatar asked Mar 23 '17 10:03

sarbuLopex


People also ask

How do you convert days to milliseconds in Java?

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));

How do you convert milliseconds to strings in Java?

toMinutes(millis) - (hours * 60); long seconds = TimeUnit. MILLISECONDS. toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60)); Use String.

How do you convert milliseconds to days hours minutes seconds in Java?

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.

How do you find the length of a millisecond?

Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).


1 Answers

Just use TimeUnit the other way round:

double days = ms / (double) TimeUnit.DAYS.toMillis(1);
like image 72
Markus Benko Avatar answered Sep 30 '22 09:09

Markus Benko