uncategorized

西元日期轉換成民國日期或是農曆日期

一般取得日期大都是採用西元年方式,但是,在某些運用方面還是必須顯示成為民國日期甚至是農曆的日期來表示

1
2
DateTime dt = DateTime.Now;
Console.WriteLine(string.Format("{0}", dt.Year));

取得民國年可以先算出西元年再去扣掉1911得到,不過,在C#內有另一種方式取得相對應的民國年,就是用System.Globalization.TaiwanCalendar類別來幫忙進行轉換,從類別名稱顧名思義就是以台灣曆法為主的一種表示法。而主要是在System.Globalization命名空間含有定義相關文化特性資訊的類別,包括語言、國家 (地區)、使用中的日曆、格式化日期模式…等,因此在這命名空間還包含了中華人民共和國跟其他的表示法。

做法只需要用到System.Globalization.TaiwanCalendarGetYear就可以達到轉換的目的,做法只有兩個步驟

  1. Datetime取得西元日期
  2. System.Globalization.TaiwanCalendar轉換成民國日期
    1
    2
    3
    4
    5
    DateTime dt = DateTime.Now;
    System.Globalization.TaiwanCalendar TC = new System.Globalization.TaiwanCalendar();
    Response.Write("西元年:" + dt.Year.ToString());
    Response.Write("民國年:" + TC.GetYear(dt));

轉換成農曆日期呢?在C#也提供TaiwanLunisolarCalendar類別來顯示農曆的日期。做法也和前一個相同,都是先取得西元日期再進行轉換

1
2
3
4
5
System.Globalization.TaiwanCalendar TC = new System.Globalization.TaiwanCalendar();
System.Globalization.TaiwanLunisolarCalendar TA = new System.Globalization.TaiwanLunisolarCalendar();
Response.Write(string.Format("西元:{0}/{1}/{2} <br>", dt.Year, dt.Month, dt.Day));
Response.Write(string.Format("明國:{0}/{1}/{2} <br>", TC.GetYear(dt), TC.GetMonth(dt), TC.GetDayOfMonth(dt)));
Response.Write(string.Format("農歷:{0}/{1}/{2} <br>", TA.GetYear(dt), TA.GetMonth(dt), TA.GetDayOfMonth(dt)));

這樣就可以很簡單達到我們的需求了