Search code examples
javalocaldateleap-year

Dealing with LocalDate and Months names


I have a .txt file, which I import into my Java program, for example ("2012.12.01"). I get the month (interesting, because I never use the getDayOfMonth().name(); part, and even so it writes the names, not the numbers (JANUARY instead of 01 or 1). So I tried to identify if the month is February or not. But even if it's true, the if returns false. Maybe it is because the month is never equal to String.

for (Changes c : list) {
                int Year = v.getDate().getYear();
                Month month= v.getDate().getMonth();
                int Day = v.getDate().getDayOfMonth();
                if (Year%4==0 && month.equals("FEBRUARY") && Day==24) 
                    leapDay = true;
            }

Solution

  • It should be

    Month.FEBRUARY.equals(month)
    

    "FEBRUARY" is a String literal, and month is a Month instance which makes them incomparable.

    There is LocalDate#isLeapYear, so your condition could be reduced to

    if (v.getDate().isLeapYear()) {
        // handle a leap year
    }