Java Code for calculating Leap Year

前端 未结 20 2613
执念已碎
执念已碎 2020-11-22 16:30

I am following \"The Art and Science of Java\" book and it shows how to calculate a leap year. The book uses ACM Java Task Force\'s library.

Here is the code the boo

20条回答
  •  感动是毒
    2020-11-22 16:56

    this answer is great but it won't work for years before Christ (using a proleptic Gregorian calendar). If you want it to work for B.C. years, then use the following adaptation:

    public static boolean isLeapYear(final int year) {
        final Calendar cal = Calendar.getInstance();
        if (year<0) {
            cal.set(Calendar.ERA, GregorianCalendar.BC);
            cal.set(Calendar.YEAR, -year);
        } else
            cal.set(Calendar.YEAR, year);
        return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
    }
    

    You can verify that for yourself by considering that year -5 (i.e. 4 BC) should be pronounced as a leap year assuming a proleptic Gregorian calendar. Same with year -1 (the year before 1 AD). The linked to answer does not handle that case whereas the above adapted code does.

提交回复
热议问题