Search code examples
javadatejcomboboxlocaldate

java.time.DateTimeException: Invalid date 'February 29' as '2017' is not a leap year Java


I am try to get starting and ending date in Java, i Have List of Month from January to December in JCombobox and Year JCombobox to Dispay Years.

First i have converted String month to month number and using this Code:

if(month_sands.getSelectedIndex() != -1){
        int monthnumber = month_sands.getSelectedIndex() + 1;

         if(monthnumber>=9)
         {
             month=String.valueOf(monthnumber);

         }else
         {
             month="0"+String.valueOf(monthnumber);
         }

    }

Then Later i have Created a String dateString to get the First and Last date of the Selected month using LocalDate, every thing is working fine but when i select February month and Year 2017 it give me Exception java.time.DateTimeException: Invalid date 'February 29' as '2017' is not a leap year

The code to Get the first and last date is

try {
        String dateString = year_sands.getSelectedItem().toString()+"-"+month+"-"+"01";   
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.US); 
        LocalDate date = LocalDate.parse(dateString, dateFormat);
        LocalDate startDate=date.withDayOfMonth(1);
        LocalDate endDate = date.withDayOfMonth(date.getMonth().maxLength());

        start_date=startDate.toString();
        end_date=endDate.toString();

        System.out.println(start_date);
        System.out.println(end_date);
    } catch (Exception e) {
        e.printStackTrace();
    }

I dont know what am doing wrong please some one help me


Solution

  • It happens because you are using maxLength() in this line:

    LocalDate endDate = date.withDayOfMonth(date.getMonth().maxLength());
    

    The method maxLength() returns the maximum length of this month in days, as the API documentation says. The month February indeed has a maximum of 29 days (just not in 2017, but this is about the month February in general, not in any particular year!).

    This should work, because it takes the length of the month in the specific year into account:

    LocalDate endDate = date.withDayOfMonth(date.lengthOfMonth());