公式:(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
static bool IsLeapYearManual(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
DateTime.DaysInMonth (推薦)
static bool IsLeapYearDateTime(int year) {
return DateTime.DaysInMonth(year, 2) == 29;
}
Calendar 類別 (支援多曆法)
using System.Globalization;
static bool IsLeapYearCalendar(int year, Calendar cal = null) {
cal ??= new GregorianCalendar();
return cal.IsLeapYear(year);
}
using System;
class LeapYearDemo {
static void Main() {
Console.Write("請輸入西元年份:");
if (int.TryParse(Console.ReadLine(), out int year) && year > 0) {
Console.WriteLine($"{year} 年是閏年嗎?");
Console.WriteLine($" 手寫邏輯:{IsLeapYearManual(year)}");
Console.WriteLine($" DateTime:{IsLeapYearDateTime(year)}");
Console.WriteLine($" Calendar:{IsLeapYearCalendar(year)}");
// 顯示 2 月天數
Console.WriteLine($" 2 月天數:{DateTime.DaysInMonth(year, 2)}");
} else {
Console.WriteLine("輸入無效,請輸入正整數年份。");
}
}
// 上述三個靜態方法放這裡...
}
| 方法 | 耗時 | 備註 |
|---|---|---|
| 手寫邏輯 | ~12 ms | 純整數運算,最快 |
| DateTime.DaysInMonth | ~45 ms | 內部呼叫 Calendar,略有開銷 |
| Calendar.IsLeapYear | ~38 ms | 虛擬方法呼叫 |
DateTime 最小為 0001/1/1。JulianCalendar。DateTime 不處理。判斷閏年雖簡單,但理解規則來源、內建 API 差異與效能特徵,能根據專案需求 (教學示範、高效能計算、多曆法支援) 選擇最適合的實作方式。生產環境建議直接使用 DateTime.DaysInMonth,程式碼最清晰且無錯誤風險。