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 period 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 that have passed. This can be a problem if the start date is at the end of the month. Isn't there 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;
}
source
share