首页/C#语言/C#中将指定的阳历日期转化为阴历/

C#中将指定的阳历日期转化为阴历

2013-06-08
877

本文提供一种简单的方法,可以将阳历日期转换为阴历,并用中文格式输出。System.Globalization中的ChineseLunisolarCalendar可以得到阴历的年、月、日,但由于涉及到润月的问题,所以需要先处理后才能输出。不知道微软为什么不直接提供一个将阳历转为阴历的方法呢?

using System.Globalization;

/// 
/// 根据阳历获取指定的阴历。
/// 
/// 阳历日期。
public string ChineseDateTime(DateTime date)
{
    ChineseLunisolarCalendar ch = new ChineseLunisolarCalendar();
    int year = ch.GetYear(date);
    int month = ch.GetMonth(date);
    int leapmonth = 0;
    if (date.Month < 3 && month > 9)
    {
        leapmonth = ch.GetLeapMonth(date.Year - 1);
    }
    else
    {
        leapmonth = ch.GetLeapMonth(date.Year);
    }
    int day = ch.GetDayOfMonth(date);

    string syear = string.Empty, smonth = string.Empty, sday = string.Empty;

    string[] arryear = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
    string[] arrmonth = { "", "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月" };
    string[] arrday = { "", "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十" };

    syear = string.Format("{0}{1}{2}{3}", arryear[Convert.ToInt32(year.ToString()[0].ToString())], arryear[Convert.ToInt32(year.ToString()[1].ToString())], arryear[Convert.ToInt32(year.ToString()[2].ToString())], arryear[Convert.ToInt32(year.ToString()[3].ToString())]);
    if (leapmonth == 0 || month < leapmonth)
    {
        smonth = arrmonth[month];
    }
    else if (month == leapmonth)
    {
        smonth = "润" + arrmonth[month - 1];
    }
    else
    {
        smonth = arrmonth[month - 1];
    }
    sday = arrday[day];
    return string.Format("{0}年{1}{2}", syear, smonth, sday);
}
Copyright © 2021 技术探索 All Rights Reserved.