一次写成,没有优化代码。只是做个Demo而已。
package test.test;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarTest {
public static void main(String[] args) {
GregorianCalendar getDate = new GregorianCalendar();
getDate.set(Calendar.MONTH, 1);
int month = getDate.get(Calendar.MONTH);
System.out.print("日" + "\t");
System.out.print("月" + "\t");
System.out.print("火" + "\t");
System.out.print("水" + "\t");
System.out.print("木" + "\t");
System.out.print("金" + "\t");
System.out.print("土" + "\t");
System.out.println();
int nextMonth = month;
int i = 1;
while(true) {
getDate.set(Calendar.DAY_OF_MONTH, i);
nextMonth = getDate.get(Calendar.MONTH);
if (month != nextMonth) {
break;
}
i++;
int weekNum = getDate.get(Calendar.DAY_OF_WEEK);
if (getDate.get(Calendar.DAY_OF_MONTH) == 1) {
for (int j = 1; j < getDate.get(Calendar.DAY_OF_WEEK); j++) {
System.out.print("\t");
}
System.out.print(getDate.get(Calendar.DAY_OF_MONTH) + "\t");
} else {
System.out.print(getDate.get(Calendar.DAY_OF_MONTH) + "\t");
}
if (weekNum == 7) {
System.out.println();
}
}
}
}
以下是显示结果(2012年2月):
日 月 火 水 木 金 土
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29
(注意:Calendar里的月份是从0~11,所有将月赋值为1的时候表示的是2月份。
星期是从1~7,天也是从1开始的
方法add(Calendar.DAY_OF_MONTH, -2)表示今天的之前第二天。
getDate.set(Calendar.DAY_OF_MONTH, i); 可以用getDate.add( Calendar.DAY_OF_MONTH , 1)代替 )