TimeUnit conversion from Milliseconds to Days not working for me

Ahmad picture Ahmad · May 25, 2018 · Viewed 9.7k times · Source

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 ?

Answer

DavidW picture DavidW · May 25, 2018

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)