public class CalendarDemo {
public static void main(String[] args) {
for (int i = 1; i <= 12; i++) {
printCalender(2020, i);
}
}
/**
* 打印日历
*
* @param year
* @param month
*/
public static void printCalender(int year, int month) {
Calendar calendar = Calendar.getInstance();
//Java中月份从0月开始计数
calendar.set(year, month - 1, 1);
//Java中规定了每周第一天是星期日,所以星期日=0,星期一=1…星期六=6
int startDay = calendar.get(Calendar.DAY_OF_WEEK); //求本周第一天是星期几
int count = startDay - 1; //第一周的初始计数
int maxDay = maxDayInMonth(year, month);
System.out.println("\n"+year + "年" + month + "月日历:");
System.out.println("日\t一\t二\t三\t四\t五\t六");
fillSpace(startDay);
for (int i = 1; i <= maxDay; i++) {
System.out.print(i + "\t"); //使用制表符进行格式对齐
count++;
if (count >= 7) { //每输出7天换一次行
count = count % 7;
System.out.println();
}
}
System.out.println();
}
/**
* 初试填充
*
* @param startDay
*/
public static void fillSpace(int startDay) {
for (int i = 1; i < startDay; i++) {
System.out.print(" \t");
}
}
/**
* 返回指定年月的当月总天数
*
* @param year
* @param month
* @return
*/
public static int maxDayInMonth(int year, int month) {
int max = 30;
//判断year是否为闰年
boolean flag = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12) max = 31;
else if (month == 2 & !flag) max = 28;
else if (month == 2 & flag) max = 29;
return max;
}
}