How do I get difference between two dates in android?, tried every thing and post

I saw all the post in here and still I can't figure how do get difference between two android dates.

This is what I do:

long diff = date1.getTime() - date2.getTime();
Date diffDate = new Date(diff);

and I get: the date is Jan. 1, 1970 and the time is always bigger in two hours...I'm from Israel so the two hours is timeOffset.

How can I get normal difference???


You're close to the right answer, you are getting the difference in milliseconds between those two dates, but when you attempt to construct a date out of that difference, it is assuming you want to create a new Date object with that difference value as its epoch time. If you're looking for a time in hours, then you would simply need to do some basic arithmetic on that diff to get the different time parts.

Java:

long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

Kotlin:

val diff: Long = date1.getTime() - date2.getTime()
val seconds = diff / 1000
val minutes = seconds / 60
val hours = minutes / 60
val days = hours / 24

All of this math will simply do integer arithmetic, so it will truncate any decimal points


    long diffInMillisec = date1.getTime() - date2.getTime();

    long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);
    long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillisec);
    long diffInMin = TimeUnit.MILLISECONDS.toMinutes(diffInMillisec);
    long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);