How to get the maximum number of days in one months in Java

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.