Get the number of days in a month
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)  

解决方案 »

  1.   

    呵呵,我有简单的方法,不用管是否是润年。方法:得到下个月的一号然后减一,就是当月的最后一天,然后得到这一天的Day,就是当月的天数了。代码:
    public int getDayOfCurrentMonth(int iYear, int iMonth) {
            int iDayCount = 31;        Calendar newCalendar = Calendar.getInstance();
            newCalendar.set(iYear, iMonth+1, 1);
            newCalendar.add(Calendar.DATE, -1);
            int iDay = newCalendar.get(Calendar.DATE);
            if(iDay>10) iDayCount = iDay;
            return iDayCount;            
        }注意传过来的Month的值哟。 java中的5月,在函数里面的值其实是4。嘻嘻,我想的方法好不好?
      

  2.   

    不好意思,多了一行代码。
    那个if(iDay>10) iDayCount = iDay;不要。我当时是用来测试用的!
      

  3.   

    Calendar thisMonth = Calendar.getInstance();
    thisMonth.set(Calendar.MONTH, your月);
    thisMonth.setFirstDayOfWeek(Calendar.SUNDAY);
    thisMonth.set(Calendar.DAY_OF_MONTH,1);
    int firstIndex=thisMonth.get(Calendar.DAY_OF_WEEK)-1;
    int maxIndex=thisMonth.getActualMaximum(Calendar.DAY_OF_MONTH);
    maxIndex-firstIndex即是