我试图在一些遗留代码中调试问题.
我已将问题缩小到以下方法:
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对象处于宽松模式,因此执行规范化.规范化取决于日历实例.
原文地址:https://www.jb51.cc/java/128548.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。