如何在 Java 中查找特定年份某个月中的天数?
GregorianCalendar 是 Calendar 类的具体子类,它提供了大多数世界所使用的标准日历系统。在 Java 中,GregorianCalendar 可以处理公历以及儒略历。
我们可以通过使用 GregorianCalendar 类的 getActualMaximum() 方法来确定或查找特定年份某个月中的天数。此方法返回 GregorianCalendar 字段可具有的最大值。参数可以是 Calendar 类的任何字段。
语法
public int getActualMaximum(int field)
示例
import java.util.*; public class NoOfDaysInAMonthOfAYearTest { public static void main(String []args) { for (int i = 2000; i < 2018; i++) { Calendar calendar = new GregorianCalendar(i, Calendar.FEBRUARY, 1); int numberOfDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); System.out.println("February " + i + ": " + numberOfDays + " days"); } } }
输出
February 2000: 29 days February 2001: 28 days February 2002: 28 days February 2003: 28 days February 2004: 29 days February 2005: 28 days February 2006: 28 days February 2007: 28 days February 2008: 29 days February 2009: 28 days February 2010: 28 days February 2011: 28 days February 2012: 29 days February 2013: 28 days February 2014: 28 days February 2015: 28 days February 2016: 29 days February 2017: 28 days
广告