为什么java.util.calendar对象的值在调用get(int)后会发生变化

前端之家收集整理的这篇文章主要介绍了为什么java.util.calendar对象的值在调用get(int)后会发生变化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在一些遗留代码中调试问题.

我已将问题缩小到以下方法

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();
    }

调试
第2行cal参数是未来日期. (2015-01-06T00:00:00.000Z)

用第一个cal.get执行第3行后(cal param的值已更改(到2014-12-12T00:00:00.000Z)

为什么/怎么会这样?

以下是创建日历的位置:

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()返回XMLGregorianCalendar

解决方法

这是因为get的调用以宽松模式规范化Calendar,并在严格模式下验证它:

returns the value of the given calendar field. In lenient mode,all calendar fields are normalized. In non-lenient mode,all calendar fields are validated and this method throws an exception if any calendar fields have out-of-range values. The normalization and validation are handled by the complete() method,which process is calendar system dependent.

看起来您的Calendar对象处于宽松模式,因此执行规范化.规范化取决于日历实例.

猜你在找的Java相关文章