问题代码如下
public static Date monthLastDate(Integer year, Integer month) throws ParseException {
if (year == null || month == null || month > 12 || month < 1) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
int i = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
无论方法传入的month为何值,i值总是当前月份的最大值。
因为Calendar类在初始化时系统时间时已经设置了Calendar.DAY_OF_MONTH的最大值,当我们修改了年份和月份的值,Calendar并没有同时去修改设置对应字段的ActualMaximum的值。
方法 | 说明 |
---|---|
void clear() | 此方法设置此日历的所有日历字段值和时间值(毫秒从历元至偏移量)未定义。 |
int getActualMaximum(int field) | 此方法返回指定日历字段可能拥有的最大值,鉴于此日历时间值。 |
解决办法:
如果要修改创建的calendar的值,首先先清空calendar所有初始的默认值,然后在修改值。
可以理解为使用clear()方法清除calendar的缓存。
public static Date monthLastDate(Integer year, Integer month) throws ParseException {
if (year == null || month == null || month > 12 || month < 1) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
int i = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
问题探究
我们看一下他的set方法,当我们set字段A的值时,并不会把所有跟A相关的值同时修改掉,只是设置了一个状态,表时其他字段还没有设置。
public void set(int field, int value)
{
// If the fields are partially normalized, calculate all the
// fields before changing any fields.
if (areFieldsSet && !areAllFieldsSet) {
computeFields();
}
internalSet(field, value);
isTimeSet = false;
areFieldsSet = false;
isSet[field] = true;
stamp[field] = nextStamp++;
if (nextStamp == Integer.MAX_VALUE) {
adjustStamp();
}
}
当我们get某个字段B的值时,会调用计算所有字段的方法,计算完毕后再去取这个字段B的值。
public int get(int field)
{
complete();
return internalGet(field);
}
下面计算所有字段的方法
/**
* Fills in any unset fields in the calendar fields. First, the {@link
* #computeTime()} method is called if the time value (millisecond offset
* from the <a href="#Epoch">Epoch</a>) has not been calculated from
* calendar field values. Then, the {@link #computeFields()} method is
* called to calculate all calendar field values.
*/
protected void complete()
{
if (!isTimeSet) {
updateTime();
}
if (!areFieldsSet || !areAllFieldsSet) {
computeFields(); // fills in unset fields
areAllFieldsSet = areFieldsSet = true;
}
}
```