static ArrayList<Integer> monthsWithThirtyDays=new ArrayList<Integer>(Arrays.asList(new Integer[]{1,3,5,7,8,10,12}));
private int d, m, y;
public static boolean isValidDate(int d, int m, int y) {
if(y<=0) // Year can't be below or equal to 0
return false;
if(!(m>0 && m<=12)) // Month can't be under 0 or above 12
return false;
if(monthsWithThirtyDays.contains(m)) { // If the month has 30 days
if(!(d>0 && d<=30))// Day can't be below 0 or above 30
return false;
} else if(m==2){ // If the month is February
if(y%4==0) { // If it has 29 days
if(!(d>0 && d<=29)) //Day can't be below 0 or above 29
return false;
} else { // If it has 28 days
if(!(d>0 && d<=28)) // Day can't be below 0 or above 28
return false;
}
} else { // If the month has 31 days
if(!(d>0 && d<=31)) // Day can't be below 0 or above 31
return false;
}
return true;
}
public Date(int d, int m, int y) throws Exception {
if(isValidDate(d,m,y)) {
this.d=d; this.m=m; this.y=y;
} else {
throw new Exception();
}
}
This also deals with the 29th day of February every 4 year.
Let me know if it works (or not)
Happy coding :) -Charlie