萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> .NET 程式設計

ASP.NET 顯示農曆日期:ChineseLunisolarCalendar 完整實作與中英文對照顯示

需求:在網頁呈現中華傳統農曆日期

現代人多不諳農曆,在網頁顯示農曆不僅實用,更能傳承文化。.NET Framework 內建 System.Globalization.ChineseLunisolarCalendar 類別,提供完整農曆轉換功能,無需第三方庫。

核心類別與常數定義

public partial class ChineseDatePage : System.Web.UI.Page {
    private static readonly ChineseLunisolarCalendar calendar = new ChineseLunisolarCalendar();
    private static readonly string ChineseNumber = "〇一二三四五六七八九";
    public const string CelestialStem = "甲乙丙丁戊己庚辛壬癸"; // 十天干
    public const string TerrestrialBranch = "子丑寅卯辰巳午未申酉戌亥"; // 十二地支

    public static readonly string[] ChineseDayName = {
        "初一","初二","初三","初四","初五","初六","初七","初八","初九","初十",
        "十一","十二","十三","十四","十五","十六","十七","十八","十九","二十",
        "廿一","廿二","廿三","廿四","廿五","廿六","廿七","廿八","廿九","三十"
    };
    public static readonly string[] ChineseMonthName = {
        "正","二","三","四","五","六","七","八","九","十","十一","十二"
    };
    // ... 頁面載入與輸出邏輯
}

關鍵轉換方法

取得完整農曆字串

public string GetChineseDate(DateTime time) {
    string y = GetYear(time);
    string m = GetMonth(time);
    string d = GetDay(time);
    string sb = GetStemBranch(time);
    return $"{y}({sb})年 {m}月 {d}";
}

干支紀年 (六十甲子)

public string GetStemBranch(DateTime time) {
    int sexagenaryYear = calendar.GetSexagenaryYear(time); // 1~60
    // 取模運算對應天干地支索引 (0-based)
    char stem = CelestialStem[(sexagenaryYear % 10) - 1];
    char branch = TerrestrialBranch[(sexagenaryYear % 12) - 1];
    return $"{stem}{branch}";
}

農曆年份 (中文數字)

public string GetYear(DateTime time) {
    var sb = new StringBuilder();
    int year = calendar.GetYear(time);
    do {
        sb.Insert(0, ChineseNumber[year % 10]);
        year /= 10;
    } while (year > 0);
    return sb.ToString();
}

農曆月份 (含閏月判斷)

public string GetMonth(DateTime time) {
    int month = calendar.GetMonth(time);
    int year = calendar.GetYear(time);
    int leap = 0;
    // 正月不可能閏月,從 3 月開始檢查
    for (int i = 3; i <= month; i++) {
        if (calendar.IsLeapMonth(year, i)) { leap = i; break; }
    }
    if (leap > 0) month--; // 閏月後的月份序數減一
    return (leap == month + 1 ? "閏" : "") + ChineseMonthName[month - 1];
}

農曆日期

public string GetDay(DateTime time) {
    return ChineseDayName[calendar.GetDayOfMonth(time) - 1];
}

前端呈現

<table>
  <tr><td><%= ForignTimeNow %></td></tr>  <!-- 公曆 -->
  <tr><td><%= ChineseTimeNow %></td></tr> <!-- 農曆 -->
</table>

注意事項

  • ChineseLunisolarCalendar 支援範圍:1901/02/19 ~ 2100/01/31
  • 閏月判斷邏輯:一年最多一個閏月,發生於第 3~11 月間
  • 編碼問題:確保頁面與資料庫編碼一致(UTF-8 推薦)
  • 效能:靜態陣列查找極快,可直接用於高流量頁面

擴展應用

  • 農曆節日判斷(春節、中秋、端午等)
  • 生肖、星座計算
  • 黃曆宜忌、節氣顯示
  • 結合 DateTimeFormatInfo 實現多語系日期格式化

幾行代碼即可接入傳統曆法,展現 .NET 框架國際化支援的深度。建議封裝為獨立元件(ChineseDateHelper),供全專案複用。

copyright © 萬盛學電腦網 all rights reserved