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;

2 Answers

Andrew Tobilko On Best Solutions

It should be


"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
Jon Skeet On

I guess because the Month never equal to String.

Yes, exactly. You could either compare the Month value with Month.FEBRUARY, or just check the value returned by getMonthValue. Note that your day-of-month part is currently wrong though - and your year check is incorrect for years divisible by 100. Fortunately, you don't need to know that part - the date can only be February 29th in a leap year anyway. I'd use:

LocalDate date = v.getDate();
if (date.getMonthValue() == 2 && date.getDayOfMonth() == 29) {
    // Leap day handling