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 ?
Because you're using TimeUnit.convert backwards. Try
TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS);
or just
TimeUnit.MILLISECONDS.toDays(difference);