I'm trying to get the difference of two timestamps in days, and TimeUnit is returning completely incorrect results for me.
Here is my code:
long ts = 1522242239952L;
long now = 1527274162820L;
long difference = now - ts;
int ageInDays = (int) TimeUnit.MILLISECONDS.convert(difference, TimeUnit.DAYS);
int ageInDays2 = (int) (difference/(1000 * 60 * 60 * 24));
System.out.println(ageInDays);
System.out.println(ageInDays2);
Output is:
-1756844032
58
Why is the TimeUnit calculation so incorrect ?
For example, to calculate the number days from milliseconds, the following statement would work: long days = TimeUnit. MILLISECONDS. toDays(milliseconds);
How to Convert Milliseconds to Days. To convert a millisecond measurement to a day measurement, divide the time by the conversion ratio. The time in days is equal to the milliseconds divided by 86,400,000.
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.
In Java, we can use the built-in methods: toMinutes() - to convert milliseconds to minutes. toSeconds() - to convert milliseconds to seconds.
Because you're using TimeUnit.convert backwards. Try
TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS);
or just
TimeUnit.MILLISECONDS.toDays(difference);
Ref: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html#convert(long,%20java.util.concurrent.TimeUnit)
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