Your calculation (and the implementation in one of the answers) only works for system that run in a timezone that doesn't know daylight saving times. For e.g. the german timezone (where I reside), the duration of 2018-03-24 03:00:00
and 2018-03-25 03:00:00
I think you expect to be one day with the only problem that that particular day only has 23 hours.
If you want to stick with the standard classes, the JVM provides, you can use a Calendar and add day after day to it until the underlying date is after the second date. Here is an example (without sanity checks e.g. that the first date is actually before the second one; you will run into an endless loop in the other case). The example sets the timezone to be used explicitly, so it should show the same result on your system as well:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class CalcDuration {
public final static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
Date d1 = sdf.parse("2018-03-24 03:00:00");
Date d2 = sdf.parse("2018-03-25 03:00:00");
System.out.println("duration1: " + getDuration(d1, d2));
}
private static int getDuration(Date d1, Date d2) {
Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
c.setTime(d1);
int days = 0;
while (true) {
c.add(Calendar.DAY_OF_YEAR, 1);
if (c.getTime().after(d2)) {
return days;
}
days++;
}
}
}