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

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

Leave a Comment