package Date;
import java.util.Calendar;
public class MyCalendar {
public static void main(String[] args) {
showCalendar(2007, 11);
}
/*
* 显示指定年月的日历
*/
public static void showCalendar(int year, int month) {
int days = daysOfMonth(year,month); //当月有多少天
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year) ;
cal.set(Calendar.MONTH, month -1 );
cal.set(Calendar.DATE, 1);
int week = cal.get(Calendar.DAY_OF_WEEK); //1号是星期几
int writeSpaceLen = week - 1 ; //空白的长度
String[] calStr = new String[writeSpaceLen + days];
//填空白
for(int i = 0; i < writeSpaceLen ;i++ ) {
calStr[i] = " "; //两个空格
}
//填日期
for(int i = writeSpaceLen,j=1 ; i< calStr.length; i++,j++) {
calStr[i] = j<10 ? " "+j : ""+j ;
}
//输出
System.out.println(" " + year + "年"+month + "月");
System.out.println("日 一 二 三 四 五 六");
System.out.println("--------------------");
for(int i=1;i<=calStr.length;i++){
System.out.print(calStr[i-1] + " ");
if(i % 7 == 0) {
System.out.println();
}
}
}
/*
* 返回指定年月的天数
*/
public static int daysOfMonth(int year, int month) {
int days = 31;
switch (month) {
case 4:
case 6:
case 9:
case 11:
days = 30;break;
case 2:
days = (year % 400 == 0 || year % 4 == 0 && year % 100 != 0) ? 29
: 28;
break;
}
return days;
}
}
阅读(1228) | 评论(0) | 转发(0) |