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()
Use java.time.Duration
:
Duration diff = Duration.between(instant2, instant1);
System.out.println(diff);
This will print something like
PT109H27M21S
This means a period of time of 109 hours 27 minutes 21 seconds. If you want someting more human-readable — I’ll give the Java 9 version first, it’s simplest:
String formattedDiff = String.format(Locale.ENGLISH,
"%d days %d hours %d minutes %d seconds",
diff.toDays(), diff.toHoursPart(), diff.toMinutesPart(), diff.toSecondsPart());
System.out.println(formattedDiff);
Now we get
4 days 13 hours 27 minutes 21 seconds
The Duration
class is part of java.time
the modern Java date and time API. This is bundled on newer Android devices. On older devices, get ThreeTenABP and add it to your project, and make sure to import org.threeten.bp.Duration
and other date-time classes you may need from the same package.
Assuming you still haven’t got the Java 9 version, you may subtract the larger units in turn to get the smaller ones:
long days = diff.toDays();
diff = diff.minusDays(days);
long hours = diff.toHours();
diff = diff.minusHours(hours);
long minutes = diff.toMinutes();
diff = diff.minusMinutes(minutes);
long seconds = diff.toSeconds();
Then you can format the four variables as above.
A Date
represents a point in time. It was never meant for representing an amount of time, a duration, and it isn’t suited for it. Trying to make that work would at best lead to confusing and hard-to-maintain code. You don’t want that, so please don’t.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
to Java 6 and 7