中國畢竟是一個文明大國,有一些自己悠久的歷史文化傳統,農歷就是其中之一,它對指導農業生產有着極為重要的意義,還有春節等一些傳節日並沒有因為使用公元紀年而消失,在程序開發種我們也經常會遇到一些需要在公歷與農歷之間進行 轉換,在1.1之前大家都是采用了第三方的算法(我也采用過),現在在.net2.0種已經提供了這種功能了。下面我就以幾個簡單的例子展示它的用法。
using System; using System.Collections.Generic; using System.Text; using System.Globalization; /** * 說明:在東亞各國,除了通用的公元紀年之外,還有各自以前使用的陰歷紀年法,在.net2.0種增加了針對東亞各國的日歷類EastAsianLunisolarCalendar, * 它是一個抽象類,有各種針對不同國家的的子類,其中ChineseLunisolarCalendar就是針對中國的日歷類,它提公元紀年與中國傳統農歷紀年之間的相互轉換 * 利用它可以計算天干地支等有關農歷的信息,本程序就是來簡單展示這個類的用法。它能計算的農歷范圍從公歷1901-2-19至2101-1-28。 * 作者:周公 * 日期:2007-11-21 * 最后維護日期:2010-01-05 * 首發地址:http://blog.csdn.net/zhoufoxcn/archive/2007/11/21/1896258.aspx */ namespace ChineseCalendar { public class Calendar { private static ChineseLunisolarCalendar chineseDate = new ChineseLunisolarCalendar(); static void Main(string[] args) { //ChineseLunisolarCalendar chineseDate = new ChineseLunisolarCalendar(); ShowYearInfo(); ShowCurrentYearInfo(); Console.ReadLine(); } /// <summary> /// 展示陰歷年份信息 /// </summary> public static void ShowYearInfo() { for (int i = chineseDate.MinSupportedDateTime.Year; i < chineseDate.MaxSupportedDateTime.Year; i++) { Console.WriteLine("年份:{0},月份總數:{1},總天數:{2},干支序號:{3}", i, chineseDate.GetMonthsInYear(i),chineseDate.GetDaysInYear(i) ,chineseDate.GetSexagenaryYear(new DateTime(i,3,1))); } } /// <summary> /// 展示當前年份信息 /// </summary> public static void ShowCurrentYearInfo() { int lYear=chineseDate.GetYear(DateTime.Now); int lMonth=chineseDate.GetMonth(DateTime.Now); int lDay=chineseDate.GetDayOfMonth(DateTime.Now); /** GetLeapMonth(int year)方法返回一個1到13之間的數字, * 比如:1、該年陰歷2月有閏月,則返回3 * 如果:2、該年陰歷8月有閏月,則返回9 * GetMonth(DateTime dateTime)返回是當前月份,忽略是否閏月 * 比如:1、該年陰歷2月有閏月,2月返回2,閏2月返回3 * 如果:2、該年陰歷8月有閏月,8月返回8,閏8月返回9 */ int leapMonth = chineseDate.GetLeapMonth(lYear);//獲取第幾個月是閏月,等於0表示本年無閏月 //如果今年有閏月 if (leapMonth > 0) { //閏月數等於當前月份 if (lMonth == leapMonth) { Console.WriteLine("今年的陰歷日期:{0}年閏{1}月{2}日。", lYear, lMonth - 1, lDay); } else if (lMonth > leapMonth)// { Console.WriteLine("今年的陰歷日期:{0}年{1}月{2}日。", lYear, lMonth - 1, lDay); } else { Console.WriteLine("今年的陰歷日期:{0}年{1}月{2}日。", lYear, lMonth, lDay); } } else { Console.WriteLine("今年的陰歷日期:{0}年{1}月{2}日。", lYear, lMonth, lDay); } Console.WriteLine("今天的公歷日期:" + DateTime.Now.ToString("yyyy-MM-dd")); Console.WriteLine("今年陰歷天數:{0},今年{1}閏年", chineseDate.GetDaysInYear(DateTime.Now.Year),(chineseDate.IsLeapYear(DateTime.Now.Year)==true)?"是":"不是"); Console.WriteLine("今年農歷每月的天數:");//注意:如果有13個數字表示當年有閏月 for (int i = 1; i <= chineseDate.GetMonthsInYear(DateTime.Now.Year); i++) { Console.Write("{0,-5}",chineseDate.GetDaysInMonth(DateTime.Now.Year,i)); } } } }
當前時間的運行效果:
2009年閏5月第一天的運行效果(手動調整了系統時間):
閏5月過后第一天的效果:
經過修正算法之后的正常顯示結果,原來的問題是在公歷2010年年初、農歷2009年年末這樣陰歷有閏月的年份會出現錯誤情況。