Question

Calculating the difference between two dates (java.util.Date) in terms of no. of days look like very simple and we can find different ways to do that. I used the following code to calculate the date difference:

  public static long daysBetween(Calendar startDate, Calendar endDate) {
        Calendar date = (Calendar) startDate.clone();
        long daysBetween = 0;
        while (date.before(endDate)) {
            date.add(Calendar.DAY_OF_MONTH, 1);
            daysBetween++;
        }
        return daysBetween;
    }

In main(), I used the following two dates :

    Calendar c1 = Calendar.getInstance();
    c1.set(2011, 1, 1);
    Calendar c2 = Calendar.getInstance();
    c2.set(2011, 1, 31);

    long difference = daysBetween(c1, c2); // 

But the value of the variable difference is not consistent. It is sometimes 30 and sometimes 31. So, why that might have happened.

Is there any solution to use the method results a consistent output ?

Was it helpful?

Solution

You're setting the date part of the calendars, but not the time part.

Sometimes the clock will tick between the calls to getInstance() and sometimes it won't, hence the inconsistency.

Options:

  • Set the time as well as the date, e.g. to midnight
  • Use a better date/time library - Joda Time - which has a more suitable representation (LocalDate). An important moral here is that if you can find a type which represents the exact information you have, and nothing else, that's likely to be a good fit and cause fewer complications.

Using LocalDate, you wouldn't even have to do the loop as Joda Time has good support for computing the differences between two values anyway.

LocalDate date1 = new LocalDate(2011, 1, 1);
LocalDate date2 = new LocalDate(2011, 1, 31);
Days period = Days.daysBetween(days1, days2);
int days = period.getDays();

OTHER TIPS

You are only setting the year, month and day. The hours, minutes, seconds and milli-seconds are the current time (and thus different every time you run it)

I suggest you use Joda Time's LocalDate instead as it appears to does exactly what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top