Get the number of days in a monthTag(s): Date and Time


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 :
calObject.getActualMaximum(calobject.DAY_OF_MONTH) 
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)
gregCalObject.getActualMaximum(gregCalObject.DAY_OF_MONTH) 

blog comments powered by Disqus