简体   繁体   中英

Java Calendar how to validate date

I'm trying to validate a given date, but it's not working how I would like it. The user inputs a date, and it gets parsed and passed to an array, and I'm trying to validate the date is a correct date(taking into account leap years, Feb, etc) without making the code extremely lengthy.

        Calendar calendar = new GregorianCalendar(getValidYear(), getValidMonth() - 1, getValidDay());


  if( validYear < 2010 )
  {
    throw new InvalidDateException("Year must be greater than 2009");
  } else {

    if(validMonth < 1 || validMonth > 12 )
    {
      throw new InvalidDateException("Month value must be greater than or equal to 1 or less than or eqaul to 12");
    } else {

      if(validDay > calendar.getActualMaximum(Calendar.DAY_OF_MONTH) || validDay <= 0)
      {
        throw new InvalidDateException(String.format ("Day value must be greater than 0 and less than or equal to %s ",
                                                       calendar.getActualMaximum(Calendar.DAY_OF_MONTH) ) );


      } 
    }//end nested if month

  }//end nested IF year

}

If I put 2018/02/33 in and have it print for the exception it shows the date as March 05, 2018 and Im not exactly sure where these numbers are coming from. The code to parse the date is

String dateGiven[] = validDate.split("/");

  validYear = Integer.parseInt(dateGiven[0]);
  validMonth = Integer.parseInt( dateGiven[1] );
  validDay = Integer.parseInt( dateGiven[2] );

And when I build the string to show the date it prints correctly, but it is not working with Calendar and Im not sure what Im doing wrong. Any help is appreciated!

It would be easier to use Java 8 time features:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate date = LocalDate.parse("2018/02/33", formatter);

will result in a DateTimeException when date is invalid:

java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 33

Calendar is lenient by default. Quoting from the documentation of its method setLenient :

With lenient interpretation, a date such as "February 942, 1996" will be treated as being equivalent to the 941st day after February 1, 1996. With strict (non-lenient) interpretation, such dates will cause an exception to be thrown. The default is lenient.

If you want to receive an exception if an invalid date is set on the Calendar then use setLenient(false); .

Otherwise 2018/02/33 is going to be interpreted as 32 days after February 1, which is March 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM