How to find the duration of difference between two dates in java?
try the following
{
Date dt2 = new DateAndTime().getCurrentDateTime();
long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
if (diffInDays > 1) {
System.err.println("Difference in number of days (2) : " + diffInDays);
return false;
} else if (diffHours > 24) {
System.err.println(">24");
return false;
} else if ((diffHours == 24) && (diffMinutes >= 1)) {
System.err.println("minutes");
return false;
}
return true;
}
Use Joda-Time library
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
One more example Date Difference
One more Link
or with Java-8 (which integrated Joda-Time concepts)
Instant start, end;//
Duration dur = Duration.between(start, stop);
long hours = dur.toHours();
long minutes = dur.toMinutes();
The date difference conversion could be handled in a better way using Java built-in class, TimeUnit. It provides utility methods to do that:
Date startDate = // Set start date
Date endDate = // Set end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);