C#公历日期转农历日期
class LunisolarCalendaUtil
{
///<summary>
/// 十天干
///</summary>
private static string[] tg = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
///<summary>
/// 十二地支
///</summary>
private static string[] dz = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
///<summary>
/// 十二生肖
///</summary>
private static string[] sx = { "鼠", "牛", "虎", "免", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
///<summary>
/// 农历月
///</summary>
///<return s></return s>
private static string[] months = { "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二(腊)" };
///<summary>
/// 农历日
///</summary>
private static string[] days1 = { "初", "十", "廿", "三" };
///<summary>
/// 农历日
///</summary>
private static string[] days = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
///<summary>
/// 返回农历天干地支年
///</summary>
///<param name="year">农历年</param>
///<return s></return s>
private static string GetLunisolarYear(int year)
{
if (year > 3)
{
int tgIndex = (year - 4) % 10;
int dzIndex = (year - 4) % 12;
return string.Concat(tg[tgIndex], dz[dzIndex], "[", sx[dzIndex], "]");
}
throw new ArgumentOutOfRangeException("无效的年份!");
}
///<summary>
/// 返回农历月
///</summary>
///<param name="month">农历月份</param>
///<return s></return s>
private static string GetLunisolarMonth(int month)
{
if (month < 13 && month > 0)
{
return months[month - 1];
}
throw new ArgumentOutOfRangeException("无效的月份!");
}
///<summary>
/// 返回农历日
///</summary>
///<param name="day">农历天</param>
///<return s></return s>
private 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>
/// <param name="dateTime">公历日期</param>
/// <returns></returns>
public static string GetLunisolarCalenda(DateTime dateTime)
{
bool isleap = false;
Calendar calendar = new ChineseLunisolarCalendar();
int year = calendar.GetYear(dateTime);
int month = calendar.GetMonth(dateTime);
int day = calendar.GetDayOfMonth(dateTime);
//获取闰月,0 则表示没有闰月.当之前的月份都闰月存在,则需要当前月份减1
int leapMonth = calendar.GetLeapMonth(year);
if (leapMonth > 0)
{
if (leapMonth <= month)
{
if (leapMonth == month)
{
//农历闰月
isleap = true;
}
//月份修正
month--;
}
}
return string.Concat(GetLunisolarYear(year), "年", isleap ? "闰" : string.Empty, GetLunisolarMonth(month), "月", GetLunisolarDay(day));
}
}
实现效果如下:
1 static void Main(string[] args) 2 { 3 //公历转农历 4 DateTime dateTime = new DateTime(2020, 5, 23); //公历日期 5 Console.WriteLine($"公历{dateTime.ToShortDateString()}-->{ LunisolarCalendaUtil.GetLunisolarCalenda(dateTime)}"); 6 7 Console.ReadKey(); 8 }
引用内容:https://www.cnblogs.com/jackcheblog/p/7209947.html

浙公网安备 33010602011771号