简体   繁体   中英

Java Check whether Date (made of integers) is valid

I am currently setting a Date using the following function.

private Date getDate (int day, int month, int year){
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month-1, day);
    Date date = calendar.getTime();
    return date;
}

However if (31, 6, 2014) is entered, the date is simply changed to the 1st of July 2014. Is there a way that I could check whether a date is valid if my input is as above?

Thanks for your help.

Reason why you get 1st of July 2014 as output:

  • when you set the month as month-1, in this case you're setting the month as June, because the month parameter in the calendar.set() method is 0-based (January has the index 0)
  • June has 30 calendar days, so if you set the day as 31, it will overflow into July 1st; if you would've set 44 as the number of days, the output would be 14th of July 2014

To counteract this, set lenient to false:

calendar.setLenient(false);

and an exception will be thrown if the dates are out of bounds

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