java Calendar类 一个奇怪的现象

import java.util.Calendar;

import org.junit.Test;
public class CalendarDemo1 {

@Test
public void testCalendarSetMethod() throws InterruptedException {
Calendar cal1 = Calendar.getInstance();
cal1.set(2000, 7, 31, 0, 0, 0);// 2000-8-31
cal1.set(Calendar.MONTH, Calendar.SEPTEMBER);
cal1.set(Calendar.DAY_OF_MONTH, 30);
System.out.println(cal1.getTime());
}
}


输出:Sat Sep 30 00:00:00 CST 2000


import java.util.Calendar;
import org.junit.Test;

public class CalendarDemo1 {

@Test
public void testCalendarSetMethod() throws InterruptedException {

Calendar cal1 = Calendar.getInstance();
cal1.set(2000, 7, 31, 0, 0, 0);// 2000-8-31
cal1.set(Calendar.MONTH, Calendar.SEPTEMBER);
cal1.getTime();
cal1.set(Calendar.DAY_OF_MONTH, 30);
System.out.println(cal1.getTime());
}
}

输出:Mon Oct 30 00:00:00 CST 2000



根据以上理解java Calendar的set()延缓计算的。查看getTime()的源代码可以看出,对时间进行了更新。

  public final Date getTime() {
        return new Date(getTimeInMillis());
    }


    public long getTimeInMillis() {
        if (!isTimeSet) {
   updateTime();
}
        return time;
    }


 private void updateTime() {
        computeTime();
// The areFieldsSet and areAllFieldsSet values are no longer
// controlled here (as of 1.5).
        isTimeSet = true;
    }





你可能感兴趣的:(java,Date,calendar,Class,import)