Java ME - how to get the number of days per month

The Java ME class java.util.Calendar has no method getActualMaximum():

... This class was a subset of J2ME based on the JDK 1.3 Calendar class. Many methods and variables have been trimmed, while other methods have been simplified to reduce the size of this class.

Is it even possible to get the number of days in a month?

+5
source share
3 answers

I got it for work using the answer below. But thanks to Nate for giving a working example.

public static int getMaxDaysInMonth(int month, int year){
    Calendar cal=Calendar.getInstance();
    cal.set(Calendar.DATE, 1);
    cal.set(Calendar.MONTH, month+1);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.DATE, cal.get(Calendar.DATE)-1);

    return cal.get(Calendar.DATE);
}

It seems to be the shortest and seems to be working fine. Any comments?

+2
source

J2ME, Calendar.getActualMaximum(), - : , 1- , , 1- .

   private int getDaysInMonth(int month, int year) {
      Calendar cal = Calendar.getInstance();  // or pick another time zone if necessary
      cal.set(Calendar.MONTH, month);
      cal.set(Calendar.DAY_OF_MONTH, 1);      // 1st day of month
      cal.set(Calendar.YEAR, year);
      cal.set(Calendar.HOUR, 0);
      cal.set(Calendar.MINUTE, 0);
      Date startDate = cal.getTime();

      int nextMonth = (month == Calendar.DECEMBER) ? Calendar.JANUARY : month + 1;
      cal.set(Calendar.MONTH, nextMonth);
      if (month == Calendar.DECEMBER) {
         cal.set(Calendar.YEAR, year + 1);
      }
      Date endDate = cal.getTime();

      // get the number of days by measuring the time between the first of this
      //   month, and the first of next month
      return (int)((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
   }

, Calendar, Calendar.JANUARY. , 0, , 12 , . , , .

:

  int d = getDaysInMonth(Calendar.DECEMBER, 2012);
  d = getDaysInMonth(Calendar.FEBRUARY, 2012);
  d = getDaysInMonth(Calendar.FEBRUARY, 2013);

d =

31
29
28

( ).

+3

getActualMaximum Calendar

Returns the maximum value specified in the specified calendar field have, given the time value of this Calendar. For example, the actual maximum value of the MONTH field is 12 for several years, and 13 in other years in the Jewish calendar system.

Example from RoseIndia :

Calendar calendar = Calendar.getInstance();
int year = 2008;
int month = Calendar.FEBRUARY;
int date = 1;
calendar.set(year, month, date);
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Number of Days: " + days);
-1
source

All Articles