year年是包含另一天的一年(一年366天)。 回顾the年算法:
if year is divisible by 400 then
is_leap_year
else if year is divisible by 100 then
not_leap_year
else if year is divisible by 4 then
is_leap_year
else
not_leap_year
维基百科leap年的 PS算法。
1. Java ap年示例
确定给定年份是否为a年的Java示例。
DateTimeExample.java
package com.mkyong.utils;
public class DateTimeExample {
public static void main(String[] args) {
DateTimeExample obj = new DateTimeExample();
System.out.println("1993 is a leap year : " + obj.isLeapYear(1993));
System.out.println("1996 is a leap year : " + obj.isLeapYear(1996));
System.out.println("2012 is a leap year : " + obj.isLeapYear(2012));
}
public boolean isLeapYear(int year) {
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
return true;
} else {
return false;
}
}
}
输出量
1993 is a leap year : false
1996 is a leap year : true
2012 is a leap year : true
2. GregorianCalendar示例
另外,您可以使用GregorianCalendar.isLeapYear()
API。
import java.util.GregorianCalendar;
//...
public boolean isLeapYear(int year) {
GregorianCalendar cal = (
GregorianCalendar) GregorianCalendar.getInstance();
return cal.isLeapYear(year);
}
参考文献
标签: leap年
翻译自: https://mkyong.com/java/java-how-to-calculate-leap-year/