The Calendar class is an abstract class that provides methods for converting between calendar fields.
One important method, Getactualmaximum, is to return the actual maximum value for the specified calendar field.
Using this method (Calendar.getactualmaximum), we can get the number of days of the month of the year.
The code is as follows:
/** * Get the maximum number of days in a month * * @param year * @param month month (1-12) * @return The maximum number of days in a month */public int Getmaxdaybyyearmonth (int year, int month) { Calendar calendar = calendar.getinstance (); Calendar.set (Calendar.year, year-1); Calendar.set (Calendar.month, MONTH); Return Calendar.getactualmaximum (calendar.date); }
Note: The above code has two places to note:
①calendar In addition to the Getactualmaximum method, there is a similar method getmaximum, but the two methods are different:
Getactualmaximum returns the actual maximum value, Getmaximum returns the maximum possible value.
If the above code is changed to Getmaximum, then the general situation will be constant return 31 (the maximum number of days in the month is 31)
②calendar Month value range is 0-11, 0 represents January 11 for December
(This is because the month in Java follows the rules in the Roman calendar: The number of months in a year is not fixed, and the first month is January.) In Java, the value returned by Calendar.month is actually the number of months from the first month of the current month, and January returns "0" in Java, so we do +1 or 1 of the time when we are working on the month.
How to get the maximum number of days in one months in Java