原来还准备自己写算法并研究农历规则发现那太难和麻烦了光是农历的推算那就我等专门研究历法的人一下搞懂的后来发现NET类库也提供一些基础的农历类SystemGlobalizationChineseLunisolarCalendar我改装了一下如DateTime时间形式代码如下实现了 公历农历转换的功能但是只能算到~年之间的基本够日常使用了源代码如下
using System;
using SystemCollectionsGeneric;
using SystemText;
namespace System
{
/**//// <summary>
/// 中国常用农历日期时间类
///
/// </summary>
class ChinaDateTime
{
private int year month dayOfMonth;
private bool isLeap;
public DateTime time;
/**//// <summary>
/// 获取当前日期的农历年
/// </summary>
public int Year
{
get { return year; }
}
/**//// <summary>
/// 获取当前日期的农历月份
/// </summary>
public int Month
{
get { return month; }
}
/**//// <summary>
/// 获取当前日期的农历月中天数
/// </summary>
public int DayOfMonth
{
get { return dayOfMonth; }
}
/**//// <summary>
/// 获取当前日期是否为闰月中的日期
/// </summary>
public bool IsLeap
{
get { return isLeap; }
}
SystemGlobalizationChineseLunisolarCalendar cc;
/**//// <summary>
/// 返回指定公历日期的阴历时间
/// </summary>
/// <param name=time></param>
public ChinaDateTime(DateTime time)
{
cc = new SystemGlobalizationChineseLunisolarCalendar();
if (time > ccMaxSupportedDateTime || time < ccMinSupportedDateTime)
throw new Exception(参数日期时间不在支持的范围内支持范围 + ccMinSupportedDateTimeToShortDateString()+到+ccMaxSupportedDateTimeToShortDateString());
year = ccGetYear(time);
month = ccGetMonth(time);
dayOfMonth = ccGetDayOfMonth(time);
isLeap = ccIsLeapMonth(year month);
if (isLeap) month = ;
thistime = time;
}
/**//// <summary>
/// 返回当前日前的农历日期
/// </summary>
public static ChinaDateTime Now
{
get { return new ChinaDateTime(DateTimeNow); }
}
/**//// <summary>
/// 返回指定农历年月日是否为闰月的农历日期时间
/// </summary>
/// <param name=Year></param>
/// <param name=Month></param>
/// <param name=DayOfMonth></param>
/// <param name=IsLeap></param>
public ChinaDateTime(int Year int Month int DayOfMonth bool IsLeap)
{
if (Year >= ccMaxSupportedDateTimeYear || Year <= ccMinSupportedDateTimeYear)
throw new Exception(参数年份时间不在支持的范围内支持范围 + ccMinSupportedDateTimeToShortDateString() + 到 + ccMaxSupportedDateTimeToShortDateString());
if (Month < || Month > )
throw new Exception(月份必须在~范围);
cc = new SystemGlobalizationChineseLunisolarCalendar();
if(ccGetLeapMonth(Year)!=Month&&IsLeap)
throw new Exception(指定的月份不是当年的闰月);
if (ccGetDaysInMonth(Year IsLeap ? Month + : Month) < DayOfMonth || DayOfMonth < )
throw new Exception(指定的月中的天数不在当前月天数有效范围);
year = Year;
month = Month;
dayOfMonth = DayOfMonth;
isLeap = IsLeap;
time = DateTimeNow;
}
/**//// <summary>
/// 获取当前农历日期的公历时间
/// </summary>
public DateTime ToDateTime()
{
return ccToDateTime(year isLeap ? month + : month dayOfMonth timeHour timeMinute timeSecond timeMillisecond);
}
/**//// <summary>
/// 获取指定农历时间对应的公历时间
/// </summary>
/// <param name=CnTime></param>
/// <returns></returns>
public static DateTime ToDateTime(ChinaDateTime CnTime)
{
return CnTimeToDateTime();
}
/**//// <summary>
/// 获取指定公历时间转换为农历时间
/// </summary>
/// <param name=Time></param>
/// <returns></returns>
public static ChinaDateTime ToChinaDateTime(DateTime Time)
{
return new ChinaDateTime(Time);
}
/**//// <summary>