1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public static boolean validateDate(String dateStr,
boolean allowPast,
String formatStr)
{
if (formatStr == null) return false; // or throw some kinda exception, possibly a InvalidArgumentException
SimpleDateFormat df = new SimpleDateFormat(formatStr);
Date testDate = null;
try
{
testDate = df.parse(dateStr);
}
catch (ParseException e)
{
// invalid date format
return false;
}
if (!allowPast)
{
// initialise the calendar to midnight to prevent
// the current day from being rejected
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (cal.getTime().after(testDate)) return false;
}
// now test for legal values of parameters
if (!df.format(testDate).equals(dateStr)) return false;
return true;
} |