Se si hanno 3 valori interi che contengono giorno/mese/anno (quindi nessuna stringa da "parsare"), validare la data è abbastanza semplice: si crea un GregorianCalendar con i 3 dati, si imposta il calendar in modo che non sia "lenient" e si prova a fare un get di un campo. Se i dati non sono corretti, viene lanciata la eccezione IllegalArgumentException.
Esempio:
codice:
import java.util.*;
public class Prova
{
public static void main (String[] args)
{
System.out.println (isDateValid (29, 2, 2007)); // false
System.out.println (isDateValid (31, 11, 2007)); // false
System.out.println (isDateValid (31, 12, 2007)); // true
System.out.println (isDateValid (31, 13, 2007)); // false
System.out.println (isDateValid (29, 2, 2008)); // true
}
public static boolean isDateValid (int day, int month, int year)
{
GregorianCalendar cal = new GregorianCalendar (year, month-1, day);
cal.setLenient (false);
try {
cal.get (Calendar.DATE);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}