c# 公元转农历
2021-06-07 17:05
标签:sel int splay div oba ati global 没有 span c# 公元转农历 标签:sel int splay div oba ati global 没有 span 原文地址:https://www.cnblogs.com/nanfei/p/10737208.htmlvoid Main()
{
var date = new DateTime(2017,7,30);
GetLunarDisplay(date).Dump();
}
public Liststring> GetLunarYearList()
{
var q1 = "甲乙丙丁戊己庚辛壬癸";
var q2 = "子丑寅卯辰巳午未申酉戌亥";
var yearList = new Liststring>();
var index1 = 0;
var index2 = 0;
while (!(index1 == 0 && index2 == 0 && yearList.Count > 0))
{
yearList.Add(q1[index1] + "" + q2[index2] + "年");
index1 = (index1 + 1) % 10;
index2 = (index2 + 1) % 12;
}
return yearList;
}
public Liststring> GetLunarMonthList()
{
var monthList = new Liststring> { "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "腊月" };
return monthList;
}
public Liststring> GetLunarDayList()
{
var dayList = new Liststring>
{ "初一","初二","初三","初四","初五","初六","初七","初八","初九","初十"
,"十一","十二","十三","十四","十五","十六","十七","十八","十九"
,"廿一","廿二","廿三","廿四","廿五","廿六","廿七","廿八","廿九","三十"};
return dayList;
}
public string GetLunarDisplay(DateTime date)
{
var calendar = new System.Globalization.ChineseLunisolarCalendar();
//获取农历的年月日
var lunarYear = calendar.GetYear(date);
var lunarMonth = calendar.GetMonth(date);
var lunarDay = calendar.GetDayOfMonth(date);
//获取农历年,公元前2679年为第一个甲子年
var firstYear = -2697;
var yearIndex = (lunarYear - firstYear - 1) % 60; //公元纪年没有公元0年,是从1开始的,所以数学规则上要减一年
var yearDisplay = GetLunarYearList()[yearIndex];
//获取农历月
int leapMonth = calendar.GetLeapMonth(lunarYear);
var monthDisplay = GetLunarMonthList()[lunarMonth - 1];
if (lunarMonth == leapMonth)
monthDisplay = "闰" + GetLunarMonthList()[lunarMonth - 1 - 1]; //闰月月份减一
else if (leapMonth > 0 && lunarMonth > leapMonth)
monthDisplay = GetLunarMonthList()[lunarMonth - 1 - 1]; //闰月之后每个月份都要减一
//获取农历日
var dayDisplay = GetLunarDayList()[lunarDay - 1];
//组件返回农历日期
return yearDisplay + monthDisplay + dayDisplay;
}