JAVA Calendar set time, the month always adds 1

Source: Internet
Author: User
Tags set time


Code:

		Calendar calendar = Calendar.getinstance ();
		Calendar.set (Calendar.month, month-1);
		Calendar.set (Calendar.year, year);
		System.out.println (Calendar.get (Calendar.month));
		Return Calendar.getactualmaximum (Calendar.day_of_month);


The result of the test is that when the actual number of days for the month parameter month is less than 31 days, the printed month result is plus 1

Information found on the Internet: http://topic.csdn.net/u/20071030/11/cc414f35-5d1b-4bae-a1c3-21e9a7fa662e.html

My test time is 2011/10/31, the code does not set Calendar.day_of_month, the date is the current 31st, and for example, September is 30 days, the month automatically add 1, the result calendar date is 2011/10/01; If the parameter passed is February , February 2011 A total of 28 days, that calendar date is 2011/03/03

Workaround:

Calendar calendar = Calendar.getinstance ();
Calendar.set (Calendar.day_of_month, 1);  Set Date
calendar.set (Calendar.month, month-1);
Calendar.set (Calendar.year, year); Return
        Calendar.getactualmaximum (calendar.day_of_month)


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.