public static void main(String[] args) {
int year = 2023;
boolean leapYear = false; // 是否为瑞年
// 循环输出12个月份的日历
for (int month = 1; month <= 12; month++) {
int daysInMonth = 0;
int currentDay = 1; // 当前日期从1号开始
int weekday = 0; // 当前日期的星期
// 判断是否为瑞年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
leapYear = true;
}
// 打印日历头
switch (month) {
case 1:
System.out.println(" January " + year);
daysInMonth = 31;
break;
case 2:
System.out.println(" February " + year);
if (leapYear) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
case 3:
System.out.println(" March " + year);
daysInMonth = 31;
break;
case 4:
System.out.println(" April " + year);
daysInMonth = 30;
break;
case 5:
System.out.println(" May " + year);
daysInMonth = 31;
break;
case 6:
System.out.println(" June " + year);
daysInMonth = 30;
break;
case 7:
System.out.println(" July " + year);
daysInMonth = 31;
break;
case 8:
System.out.println(" August " + year);
daysInMonth = 31;
break;
case 9:
System.out.println(" September " + year);
daysInMonth = 30;
break;
case 10:
System.out.println(" October " + year);
daysInMonth = 31;
break;
case 11:
System.out.println(" November " + year);
daysInMonth = 30;
break;
case 12:
System.out.println(" December " + year);
daysInMonth = 31;
break;
default:
break;
}
System.out.println("Su Mo Tu We Th Fr Sa");
// 计算上个月的天数
Calendar lastMonth = Calendar.getInstance();
lastMonth.set(year, month - 1, 1);
int lastMonthDays = lastMonth.get(Calendar.DAY_OF_WEEK) - 1;
// 打印上个月剩余的日期
for (int i = 0; i < lastMonthDays; i++) {
System.out.print(" ");
weekday++;
}
// 打印本月的日期
for (int i = 1; i <= daysInMonth; i++) {
if (currentDay == i) {
System.out.printf("%2d*", i);
} else {
System.out.printf("%3d", i);
}
weekday++;
if (weekday == 7) {
weekday = 0;
System.out.println();
}
}
// 打印下个月开始的日期
if (weekday != 0) {
for (int i = 0; i < 7 - weekday; i++) {
System.out.print(" ");
}
}
System.out.println();
System.out.println();
}
}