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

.NET 內建 ChineseLunisolarCalendar 輕鬆實現公曆轉農曆、天干地支與生肖查詢

     編輯:關於.NET

.NET Framework 2.0 起即內建 System.Globalization.ChineseLunisolarCalendar,支援 1901/2/19 ~ 2101/1/28 之間的公農曆互轉、閏月判斷、天干地支、生肖等傳統曆法資訊。本文整理完整可用的工具類,含公曆轉農曆字串、年/月/日中文顯示、生肖查詢,並附上測試範例,開箱即用。

核心 API 快速查閱

  • GetYear / GetMonth / GetDayOfMonth:取得農曆年月日;
  • GetLeapMonth(year):取得該年閏月(0 表示無閏月);
  • GetSexagenaryYear / GetTerrestrialBranch:取得干支年與地支索引;
  • MaxSupportedDateTime / MinSupportedDateTime:支援範圍邊界。

公曆轉農曆字串完整實作

static readonly ChineseLunisolarCalendar cCalendar = new ChineseLunisolarCalendar();

public static string GetChineseDateTime(DateTime datetime)
{
    int lyear = cCalendar.GetYear(datetime);
    int lmonth = cCalendar.GetMonth(datetime);
    int lday = cCalendar.GetDayOfMonth(datetime);
    int leapMonth = cCalendar.GetLeapMonth(lyear);
    bool isLeap = false;

    if (leapMonth > 0)
    {
        if (leapMonth == lmonth) { isLeap = true; lmonth--; }
        else if (lmonth > leapMonth) lmonth--;
    }

    return $"{GetLunisolarYear(lyear)}年{(isLeap ? " 閏" : "")}{GetLunisolarMonth(lmonth)}月{GetLunisolarDay(lday)}";
}

輔助方法:天干地支年、農曆月、農曆日


// 天干、地支、生肖陣列
static readonly string[] tiangan = { "甲","乙","丙","丁","戊","己","庚","辛","壬","癸" };
static readonly string[] dizhi = { "子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥" };
static readonly string[] shengxiao = { "鼠","牛","虎","兔","龍","蛇","馬","羊","猴","雞","狗","豬" };

public static string GetLunisolarYear(int year)
{
    if (year <= 3) throw new ArgumentOutOfRangeException("無效年份");
    int tg = (year - 4) % 10;
    int dz = (year - 4) % 12;
    return $"{tiangan[tg]}{dizhi[dz]}[{shengxiao[dz]}]";
}

static readonly string[] months = { "正","二","三","四","五","六","七","八","九","十","十一","十二(臘)" };
public static string GetLunisolarMonth(int month) =>
    (month > 0 && month < 13) ? months[month - 1] : throw new ArgumentOutOfRangeException("無效月份");

static readonly string[] days1 = { "初","十","廿","三" };
static readonly string[] days = { "一","二","三","四","五","六","七","八","九","十" };
public static string GetLunisolarDay(int day)
{
    if (day <= 0 || day >= 32) throw new ArgumentOutOfRangeException("無效日期");
    if (day != 20 && day != 30)
        return days1[(day - 1) / 10] + days[(day - 1) % 10];
    return days[(day - 1) / 10] + days1[1]; // 二十、三十特殊處理
}

依公曆日期取得生肖

public static string GetShengXiao(DateTime datetime)
{
    int branch = cCalendar.GetTerrestrialBranch(cCalendar.GetSexagenaryYear(datetime));
    return shengxiao[branch - 1];
}

測試範例

// 輸入 2010-03-04
// 輸出:庚寅[虎]年正月十九
Console.WriteLine(GetChineseDateTime(new DateTime(2010, 3, 4)));
// 輸出:虎
Console.WriteLine(GetShengXiao(new DateTime(2010, 3, 4)));

幾行代碼即滿足農曆顯示、萬年曆、生肖查詢等常見需求,無需引入第三方庫。

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