Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ME - how to get number of days in month

The Java ME java.util.Calendar class does not have the getActualMaximum() method:

...This class has been subset for J2ME based on the JDK 1.3 Calendar class. Many methods and variables have been pruned, and other methods simplified, in an effort to reduce the size of this class.

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

like image 326
Pma Avatar asked Oct 06 '22 02:10

Pma


1 Answers

In J2ME, since you don't have Calendar.getActualMaximum() available, you could try something like the following: using the calculation from this answer, you could calculate the number of days between the 1st day of the month you're interested in, and the 1st day of the next month.

   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));
   }

Note that this method takes months as Calendar constants, like Calendar.JANUARY. I think the raw integer representation of those is 0-indexed, so if you pass 12 for December, the results may be wrong. I also haven't tested daylight savings time issues, so you'll have to verify that this is sufficient for your app's needs.

Use the above function like so:

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

which will yield d =

31
29
28

(for US time zones).

like image 110
Nate Avatar answered Oct 10 '22 03:10

Nate