I’m trying to validate a date input by a user using the Gregorian Calendar in java (this is a must), however whenever I test a date in December it throws up the error below.
Exception in thread "main" java.lang.IllegalArgumentException: MONTH
at java.util.GregorianCalendar.computeTime(Unknown Source)
at java.util.Calendar.updateTime(Unknown Source)
at java.util.Calendar.getTimeInMillis(Unknown Source)
at java.util.Calendar.getTime(Unknown Source)
code below
public static boolean ValidDate (int Day, int Month, int Year)
GregorianCalendar Date = new GregorianCalendar();
Date.setLenient(false);
Date.set(Year, Month, Day, 0, 0, 0);
try{
Date.getTime();
return true;
}catch (Exception e){
System.out.println("Date is invalid please try again");
return false;
}
}
I haven’t been able to turn up anything relevant on google so any help would be awesome!
With the Calendar class, although days and years are numbered 1..n (one-based), months are numbered 0-11 (zero-based), so December is not month number 12, it is month number 11.
Try calling your method specifying 11 (instead of 12) for the month parameter.
This issue is just one of the many challenging aspects of the Calendar class.
Or, better yet, use the constant Calendar.DECEMBER. You don't have to worry about whether it's 11 or 12 under the covers.
Do yourself a favor: learn and follow the Java coding standards. I'd write it this way:
public static boolean isvalidDate (int day, int month, int year)
Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
calendar.set(year, month, day, 0, 0, 0);
try {
date.getTime();
return true;
} catch (Exception e) {
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With