首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

C# 判斷閏年完整實作:規則、效能與 DateTime 內建方法

     編輯:更多程式設計知識

閏年規則 (格里曆)

  1. 能被 4 整除 → 閏年
  2. 但能被 100 整除 → 平年
  3. 除非能被 400 整除 → 閏年

公式:(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)

三種實作方式

1. 手寫邏輯 (教學用)


static bool IsLeapYearManual(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

2. 使用 DateTime.DaysInMonth (推薦)


static bool IsLeapYearDateTime(int year) {
    return DateTime.DaysInMonth(year, 2) == 29;
}

3. 使用 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("輸入無效,請輸入正整數年份。");
        }
    }
    // 上述三個靜態方法放這裡...
}

效能比較 (10M 次迴圈, Release x64)

方法耗時備註
手寫邏輯~12 ms純整數運算,最快
DateTime.DaysInMonth~45 ms內部呼叫 Calendar,略有開銷
Calendar.IsLeapYear~38 ms虛擬方法呼叫

常見誤區

  • 年份 0 不存在:格里曆從 1 年開始,DateTime 最小為 0001/1/1。
  • 儒略曆 vs 格里曆:1582 年前各國採用不同曆法,歷史專案需用 JulianCalendar。
  • 閏秒:與閏年無關,UTC 偶爾插入閏秒,DateTime 不處理。

結語

判斷閏年雖簡單,但理解規則來源、內建 API 差異與效能特徵,能根據專案需求 (教學示範、高效能計算、多曆法支援) 選擇最適合的實作方式。生產環境建議直接使用 DateTime.DaysInMonth,程式碼最清晰且無錯誤風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved