public class DateTester{
private static final long MILLISECONDS_IN_YEAR = 31556926279L;
public static void main(String[] args) {
//Note: These constructors are deprecated
//I'm just using them for a quick test
Date startDate = new Date(2013,03,01);
Date birthday = new Date(1981,01,1981);//Returns false
Date birthday2 = new Date(1972,03,20); //Returns true
Date birthday3 = new Date(1973,02,27); //Test edge cases //Returns false
Date birthday4 = new Date(1972,02,27); //Test edge cases, //Returns false
System.out.println(withinYear(birthday, startDate,40));
System.out.println(withinYear(birthday2, startDate,40));
System.out.println(withinYear(birthday3, startDate,40));
System.out.println(withinYear(birthday4, startDate,40));
System.out.println(withinYear(birthday, startDate,40));
System.out.println(withinYear(birthday2, startDate,40));
}
public static boolean withinYear(Date birthday, Date startDate, int years){
if(birthday.before(startDate)){
long difference = Math.abs(birthday.getTime() - startDate.getTime());
int yearDifference = (int) (difference/MILLISECONDS_IN_YEAR);
return yearDifference < (years +1) && yearDifference >= years;
}
return false;
}
}