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!
LocalDate.of( year , month , dayOfMonth ) // Catch exception `DateTimeParseException`
The modern approach uses the java.time classes rather than the troublesome old GregorianCalendar
class.
The java.time.LocalDate
class represents a date-only value without time-of-day and without time zone.
To validate your inputs, attempt to assemble a LocalDate
from the numbers. Unlike GregorianCalendar
, LocalDate
has sane numbering of months, 1-12 for January-December. If the numbers result in an invalid date, a DateTimeParseException
is thrown for you to catch.
try {
LocalDate ld = LocalDate.of( year , month , dayOfMonth ) ;
return true ; // true = Valid data entered for a date.
} catch ( DateTimeParseException e ) {
return false; // Exception caught, meaning invalid data-entry.
}
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.