Get the number of days in a monthTag(s): Date and Time
About cookies on this site
We use cookies to collect and analyze information on site performance and usage,
to provide social media features and to enhance and customize content and advertisements.
public static int daysInMonth(GregorianCalendar c) {
int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += c.isLeapYear(c.get(GregorianCalendar.YEAR)) ? 1 : 0;
return daysInMonths[c.get(GregorianCalendar.MONTH)];
}
Actually, the Calendar class provides a method to that very simply. For a given Calendar or
GregorianCalendar object :
In the Java API documentation there is a note saying that
The version (getActualMaximum()) of this function on Calendar uses
an iterative algorithm to determine the actual maximum value for the field.
There is almost always a more efficient way to accomplish this
(in most cases, you can simply return getMaximum()).
GregorianCalendar overrides this function with a more efficient implementation. So
it looks like it's a lot more efficient to call getActualMaximum from a GregorianCalendar
object than a Calendar object. (Thanks to P. Harris for the tip)