I was just trying out the java.util.Calendar method getActualMaximum() to see if I can get the maximum number of days in a month given the year. Here’s my code:
public static void main(String[] args) {
Calendar c = Calendar.getInstance(); // today is July 29, 2012
System.out.println(c.get(Calendar.MONTH) + " " + c.getActualMaximum(Calendar.DATE) + " " + c.get(Calendar.YEAR));
c.set(Calendar.MONTH, Calendar.FEBRUARY); // set to February 2012
System.out.println(c.get(Calendar.MONTH) + " " + c.getActualMaximum(Calendar.DATE) + " " + c.get(Calendar.YEAR));
c.set(Calendar.YEAR, 2011); // set year to 2011, now February 2011
System.out.println(c.get(Calendar.MONTH) + " " + c.getActualMaximum(Calendar.DATE) + " " + c.get(Calendar.YEAR));
}
The output I’m expecting is:
6 31 2012 // last day of July 2012 is 31
1 29 2012 // last day of Feb 2012 is 29
1 28 2011 // last day of Feb 2011 is 28
However, this is what I’m getting:
6 31 2012
1 29 2012
2 31 2011 // HUH?
(In java.util.Calendar, the month values start from 0 to 11 for January to December, while the days of the months themselves start with 1.)
Why was the month suddenly set to Calendar.MARCH? What’s going on here, and what can I do to get the last days of a given month and year correctly? I’m exploring the method because I don’t want to set up my own array of booleans where it’s true for indices that represent 31-day months and false for not.
I believe the calendar is remembering how many days into the year you are. in 2012 you were on day 31 + 29 = Feb 29. In 2011 that was March 1. Then you asked for the actual maximum of that month, which (for March) is 31.
Calendar API is horrible.
You should just set the year and month directly before asking for the actual maximum in your use-case.