javacalendar

How do I determine time passed between two Calendar Objects in Java?


What is the best way to count the amount of time between two Calendar dates in java. I am writing a method that determines the number of months that pass between two dates and returns a boolean based on a predefined term of months. This is my code(does not work correctly).

This code always returns false. Also this code does not take into account the number of days passed. This could be a problem if the start date is at the end of a month. Is there not a simple compareTo method?

private boolean hasMatured()
{
    Calendar now = Calendar.getInstance();

    Calendar start = (Calendar) super.dateOpened.clone();

    int nowYear = now.get(Calendar.YEAR);
    int nowMonth = now.get(Calendar.MONTH);

    int startYear = start.get(Calendar.YEAR);
    int startMonth = start.get(Calendar.MONTH);

    int monthsElapsed = (nowYear - startYear) * 12 + (nowMonth - startMonth);

    return monthsElapsed>PERIOD_IN_MONTHS;
}

Solution

  • int nowYear = now.get(Calendar.YEAR);
    int nowMonth = now.get(Calendar.MONTH);
    
    int startYear = now.get(Calendar.YEAR);
    int startMonth = now.get(Calendar.MONTH);
    
    int monthsElapsed = (nowYear - startYear) * 12 + (nowMonth - startMonth);