-3

What my understanding is like:

  1. for a year its like 365.2425 to be precise so if we take for a year (365.24 ) it leaves .24 days right it is like 6 hrs for every 4 years it adds up to 24 hrs so it will create a day we add this to feb 29 so why we are leaving the remaining

  2. so here we leave the balance .25 days right if i am wrong correct me on this guys for every 100 year we leave .25 days (6 hrs) it adds up to 24 hrs in every 400th year we add the extra day in feb make it as a leap year

These are my understanding about the problem I saw the leap year solution.

In that one why do we check if the year is not divisible by 100? what is the need for the 100 what is the logic behind this?

     // Else If a year is multiple of 100,
    // then it is not a leap year
    if (year % 100 == 0)
        return false;

Why do we check with the 100?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 4
    Every year that is divisible by 4 is a leap year. Unless it's divisible by 100 then it isn't. Unless it's also divisible by 400, then it is. There are 365 days in a year. Unless it's a leap year, then there are 366 days. A year is how long it takes Earth to orbit the Sun. A day is how long it takes Earth to complete one full axial rotation. Those two phenomena do not precisely correlate. So we have leap days. And leap seconds! – Elliott Frisch Jul 17 '22 at 06:09
  • 2
    https://en.wikipedia.org/wiki/Leap_year .. – kleopatra Jul 17 '22 at 08:28

1 Answers1

1

Time is complicated, always use/reference library, don't try to implement yourself.
What you see is probably an example reinventing the wheel and do it wrong.

Check JavaDoc of Year#isLeapYear and corresponding source.

Checks if the year is a leap year, according to the ISO proleptic calendar system rules. This method applies the current rules for leap years across the whole time-line. In general, a year is a leap year if it is divisible by four without remainder. However, years divisible by 100, are not leap years, with the exception of years divisible by 400 which are.

For example, 1904 is a leap year it is divisible by 4. 1900 was not a leap year as it is divisible by 100, however 2000 was a leap year as it is divisible by 400.

The calculation is proleptic - applying the same rules into the far future and far past. This is historically inaccurate, but is correct for the ISO-8601 standard.

    public static boolean isLeap(long year) {
        return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
    }

So the logic year % 100 == 0 in your code is not correct, as we need to exclude the case for year is divisible by 400.

P.S. & 3 is just optimization of % 4

samabcde
  • 6,988
  • 2
  • 25
  • 41