Finding Leap Years in Java – 在Java中寻找闰年

最后修改: 2019年 1月 23日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll demonstrate several ways to determine if a given year is a leap year in Java.

在本教程中,我们将演示在Java中确定某个年份是否是闰年的几种方法。

A leap year is a year that is divisible by 4 and 400 without a remainder. Thus, years that are divisible by 100 but not by 400 don’t qualify, even though they’re divisible by 4.

闰年是指能被4和400整除而没有余数的年份。因此,能被100除以但不能被400除以的年份就不符合条件,即使它们能被4除以。

2. Using the Pre-Java-8 Calendar API

2.使用Pre-Java-8日历API

Since Java 1.1, the GregorianCalendar class allows us to check if a year is a leap year:

从Java 1.1开始,GregorianCalendar类允许我们检查某年是否是闰年。

public boolean isLeapYear(int year);

As we might expect, this method returns true if the given year is a leap year and false for non-leap years.

正如我们所期望的,如果给定的年份是闰年,该方法返回true,如果是非闰年则返回false

Years in BC (Before Christ) need to be passed as negative values and are calculated as 1 – year. For example, the year 3 BC is represented as -2, since 1 – 3 = -2.

公元前的年份(Before Christ)需要作为负值传递,并按1-计算。例如,公元前3年被表示为-2,因为1-3=-2。

3. Using the Java 8+ Date/Time API

3.使用Java 8+日期/时间API</b

Java 8 introduced the java.time package with a much better Date and Time API.

Java 8 引入了java.time包,并提供了更好的日期和时间 API

The class Year in the java.time package has a static method to check if the given year is a leap year:

java.time包中的Year类有一个static方法来检查给定年份是否是闰年。

public static boolean isLeap(long year);

And it also has an instance method to do the same:

它也有一个实例方法来做同样的事情。

public boolean isLeap();

4. Using the Joda-Time API

4.使用Joda-Time API

The Joda-Time API is one of the most used third-party libraries among the Java projects for date and time utilities. Since Java 8, this library is in maintainable state as mentioned in the Joda-Time GitHub source repository.

Joda-Time API是Java项目中使用最多的日期和时间实用程序的第三方库之一。自Java 8以来,该库处于可维护状态,如Joda-Time GitHub源码库中所述。

There is no pre-defined API method to find a leap year in Joda-Time. However, we can use their LocalDate and Days classes to check for leap year:

在Joda-Time中没有预先定义的API方法来查找闰年。然而,我们可以使用他们的LocalDateDays类来检查闰年的情况。

LocalDate localDate = new LocalDate(2020, 1, 31);
int numberOfDays = Days.daysBetween(localDate, localDate.plusYears(1)).getDays();

boolean isLeapYear = (numberOfDays > 365) ? true : false;

5. Conclusion

5.总结

In this tutorial, we’ve seen what a leap year is, the logic for finding it, and several Java APIs we can use to check for it.

在本教程中,我们已经看到了什么是闰年,找到它的逻辑,以及我们可以用来检查它的几个Java API。

As always, code snippets can be found over on GitHub.

一如既往,代码片段可以在GitHub上找到