C# 阳历转阴历

前言

需求:需要根据当前日期,获取阴历日期。原文传送门

具体实现

代码如下图所示:

声明农历日月,代码如下所示:

/// <summary>
/// 农历日月
/// </summary>
private static string[] months = {
  "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"
};
private static string[] days1 = { "初", "十", "廿", "三" };
private static string[] days = {
   "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"
};

返回农历月,代码如下所示:

/// <summary>
/// 返回农历月
/// </summary>
/// <param name="month">月份</param>
/// <returns></returns>
public static string GetLunisolarMonth(int month)
{
    if (month < 13 && month > 0)
    {
       return months[month - 1];
    }
    throw new ArgumentOutOfRangeException("无效的月份!");
}

返回农历日,代码如下所示:

/// <summary>
/// 返回农历日
/// </summary>
/// <param name="day"></param>
/// <returns></returns>
public static string GetLunisolarDay(int day)
{
    if (day > 0 && day < 32)
    {
        if (day != 20 && day != 30)
        {
            return string.Concat(days1[(day - 1) / 10], days[(day - 1) % 10]);
        }
        else
        {
            return string.Concat(days[(day - 1) / 10], days1[1]);
         }
      }
     throw new ArgumentOutOfRangeException("无效的日!");
}

最后,传入日期。代码如下所示:

/// <summary>
/// 阳历转阴历
/// </summary>
/// <returns></returns>
public string GetYdataBydata(DateTime m_yData)
{
    string lunarDate = string.Empty;
    ChineseLunisolarCalendar cCalendar = new ChineseLunisolarCalendar();
    int lyear = cCalendar.GetYear(m_yData);
    int lmonth = cCalendar.GetMonth(m_yData);
    int lday = cCalendar.GetDayOfMonth(m_yData);
    //获取闰月, 0 则表示没有闰月
    int leapMonth = cCalendar.GetLeapMonth(lyear);
    bool isleap = false;
    if (leapMonth > 0)
    {
        if (leapMonth == lmonth)
        {
           //闰月
           isleap = true;
           lmonth--;
         }
         else if (lmonth > leapMonth)
         {
            lmonth--;
         }
   }
   lunarDate= string.Concat(isleap ? "闰" : string.Empty, GetLunisolarMonth(lmonth), "月", GetLunisolarDay(lday));
    return lunarDate;
}
原文地址:https://www.cnblogs.com/ZengJiaLin/p/14464817.html