前言
Unity农历和公历相互转换,使用 System.Globalization.ChineseLunisolarCalendar 实现,但是需要注意的是在.NET2.0是无法调用GetMonth等方法的,在.NET2.0中,方法被标记为[MonoTODO]。
农历转公历
/// <summary>
/// 农历转公历
/// 需.net4.6可用
/// </summary>
/// <param name="time">2021-07-24</param>
/// <returns>2021-08-31</returns>
public static string LunarToSolar( string time)
{
System.Globalization.ChineseLunisolarCalendar cncld = new System.Globalization.ChineseLunisolarCalendar();
int year = Convert.ToInt32(time.Split('-')[0]);
int month = Convert.ToInt32(time.Split('-')[1]);
int day = Convert.ToInt32(time.Split('-')[2]);
int flag = cncld.GetLeapMonth(year);
DateTime dtnl = cncld.ToDateTime(year, month, day, 0, 0, 0, 0);
dtnl = flag > 0 ? dtnl.AddMonths(1) : dtnl;
return dtnl.ToString("yyyy-MM-dd");
}
公历转农历
/// <summary>
/// 公历转农历
/// 需.net4.6可用
/// </summary>
/// <param name="time">2021-08-31</param>
/// <returns>2021-07-24</returns>
public static string SolarToLunar( string time)
{
System.Globalization.ChineseLunisolarCalendar cncld = new System.Globalization.ChineseLunisolarCalendar();
DateTime dt = DateTime.Parse(time);
int year = cncld.GetYear(dt);
int flag = cncld.GetLeapMonth(year);
int month = flag > 0 ? cncld.GetMonth(dt) - 1 : cncld.GetMonth(dt);
int day = cncld.GetDayOfMonth(dt);
return $"{
year}-{
(month.ToString().Length == 1 ? "0" + month : month + "")}-{
(day.ToString().Length == 1 ? "0" + day : day + "")}";
}