Why Java util. The value of the calendar object will change after calling get (int)

I try to debug problems in some legacy code.

I have narrowed the problem down to the following methods:

public String formatDateTimeFromCalendar (Calendar cal){
        StringBuffer sb = new StringBuffer();
        String hr = ""+cal.get(Calendar.HOUR_OF_DAY);
        sb.append(String.format("%02d",hr)); 
        sb.append(":");
        sb.append(String.format("%02d",cal.get(Calendar.MINUTE)));
        sb.append( " on ");
        sb.append(String.format("%02d",cal.get(Calendar.DAY_OF_MONTH)));
        sb.append( "/");
        sb.append(String.format("%02d",cal.get(Calendar.MONTH)+1));
        sb.append( "/");
        sb.append( cal.get(Calendar.YEAR));
        return sb.toString();
    }

The cal parameter in the second line of debugging is the future date (2015-01-06T00:00:00.000Z)

Use the first cal After get executes line 3 (the value of cal param has been changed (to 2014-12-12t00:00:00.000z)

Why / how did this happen?

Here is where you created your calendar:

Calendar startDateAndTime = Calendar.getInstance();
        startDateAndTime.setTime(response.getStartDate().toGregorianCalendar().getTime());
        startDateAndTime.set(Calendar.HOUR_OF_DAY,response.getStartTime().getHour());
        startDateAndTime.set(Calendar.MINUTE,response.getStartTime().getMinute());
        startDateAndTime.set(Calendar.SECOND,response.getStartTime().getSecond());
        startDateAndTime.set(Calendar.MILLISECOND,response.getStartTime().getMillisecond());

response. Getstartdate() returns xmlregionancalendar

Solution

This is because the call to get normalizes calendar in loose mode and verifies it in strict mode:

It looks like your calendar object is in loose mode, so perform normalization Normalization depends on calendar instances

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>