Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeUnit conversion from Milliseconds to Days not working for me

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 ?

like image 450
Ahmad Avatar asked May 25 '18 18:05

Ahmad


People also ask

How do you use TimeUnit class to convert milliseconds to days?

For example, to calculate the number days from milliseconds, the following statement would work: long days = TimeUnit. MILLISECONDS. toDays(milliseconds);

How do you convert milliseconds to days?

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.

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 convert milliseconds to seconds in Java?

In Java, we can use the built-in methods: toMinutes() - to convert milliseconds to minutes. toSeconds() - to convert milliseconds to seconds.


1 Answers

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)

like image 181
DavidW Avatar answered Sep 20 '22 15:09

DavidW