Issue with Gregorian Calendar [duplicate]

别说谁变了你拦得住时间么 提交于 2019-12-24 08:58:01

问题


We are using the below code snippet to get number of days for the provided month and year. For 02 and 2011, It returns the no of days as 31 ( which is not the case). for 02 and 2016, it returns the no of days as 29.

Any clues.

package Processes.BSAInvoiceInquiry.ExternalCall.PaymentStatusInquiry;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class PaymentStatusInquiryJavaCode {

    protected int year = 0;
    protected int month = 0;
    protected int days = 0;

    public void invoke() throws Exception {

        PaymentStatusInquiryJavaCode a = new PaymentStatusInquiryJavaCode();

        System.out.println("Year  " + year);
        System.out.println("Month  " + month);

        Calendar calObj = new GregorianCalendar();
        calObj.set(Calendar.YEAR, year);
        calObj.set(Calendar.MONTH, month - 1);
        System.out.println("Month  " + Calendar.MONTH);
        int numDays = calObj.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.println("No of the days in the month is   " + numDays);
        days = numDays;

    }
}

回答1:


This is just another unexpected behavior of Calendar, see this, you can fix it by clear after the creation:

Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 1);
System.out.println(calendar.getActualMaximum(calendar.DAY_OF_MONTH)); //28

The use of outdated Calendar should be avoided. In java8, this can be done by:

YearMonth yearMonth = YearMonth.of(2011, 2);
int lengthOfMonth = yearMonth.lengthOfMonth();
System.out.println(lengthOfMonth); //28



回答2:


To complete user6690200's answer it returns 29 for 2016 because it's the 29th today and 2016 was a leap year and had a 29th of february. 2011 wasn't a leap year so it actually returns the number for the next month(March which has 31 days).




回答3:


try

// month 1 based    
new Calendar.Builder().setDate(year, month-1, 1).build().getActualMaximum(DAY_OF_MONTH)

the problem is none

calObj.set(DAY_OF_MONTH, 1);


来源:https://stackoverflow.com/questions/50085796/issue-with-gregorian-calendar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!