功能概覽
- 列印指定年份完整年曆(12 月)
- 列印指定年份、月份的單月曆
- 列印當前月份曆表,並以
:)27(: 標記今日
- 支援西元年份輸入,自動處理閏年
核心類別設計:HongtenDate
public class HongtenDate {
private int year;
private int whatDayOnJanuaryOne; // 1/1 是星期幾 (0=Sun .. 6=Sat)
public HongtenDate() { ... } // 預設當前年份
public HongtenDate(int year) { ... } // 指定年份
public void printCalendar() { ... } // 印全年
public void printMonthOfYear(int mon) { ... } // 印指定月
public void printCurrentMonth() { ... } // 印當月含今日標記
}
關鍵演算法
- 取得 1/1 星期:用
Calendar 解析 yyyy-01-01 取 DAY_OF_WEEK。
- 單月列印:設定
Calendar 為該月 1 號,取得起始星期與天數,迴圈印製,遇週六換行。
- 全年列印:依月份天數(31/30/28/29)呼叫對應列印邏輯,累加
whatDayOnJanuaryOne 推算下月首日星期。
- 閏年判斷:
year % 4 == 0(簡化版,未排除百年非閏)。
程式碼精華片段
列印指定月(含今日標記)
public void printCurrentMonth() {
GregorianCalendar now = new GregorianCalendar();
Date today = new Date();
now.setTime(today);
int toDay = now.get(Calendar.DAY_OF_MONTH);
int month = now.get(Calendar.MONTH);
now.set(Calendar.DAY_OF_MONTH, 1);
int week = now.get(Calendar.DAY_OF_WEEK);
System.out.println("日\t一\t二\t三\t四\t五\t六");
for (int i = Calendar.SUNDAY; i < week; i++) System.out.print("\t");
while (now.get(Calendar.MONTH) == month) {
int day = now.get(Calendar.DAY_OF_MONTH);
if (day < 10) {
System.out.print((day == toDay) ? ":)" + day + "(:\t" : " " + day + "\t");
} else {
System.out.print((day == toDay) ? ":)" + day + "(:\t" : day + "\t");
}
if (week == Calendar.SATURDAY) System.out.println();
now.add(Calendar.DAY_OF_MONTH, 1);
week = now.get(Calendar.DAY_OF_WEEK);
}
}
主程式測試
public static void main(String[] args) {
HongtenDate date = new HongtenDate(); // 當前年
date.printCurrentMonth(); // 印本月
// date.printCalendar(); // 印全年
// date.printMonthOfYear(4); // 印指定月
HongtenDate hd = new HongtenDate(2014); // 指定年
hd.printMonthOfYear(1); // 印 2014 年 1 月
}
輸出範例(2013 年 4 月,今日 27 號)
日 一 二 三 四 五 六
2 3 4 5 6
8 9 10 11 12 13
15 16 17 18 19 20
22 23 24 25 26 :)27(:
29 30