西历转和历函数

     对日开发中可能会经常遇到日期格式的转换,最头疼的就是系统时间转日本和历的问题。

     多数的时候大家都是自己写函数来计算日本各时期皇帝的在位时间来进行转换的,其实.NET中已经内置日本这一特殊的日历计算算法。

     运用Globalization下的Calendar和Calendar 类我们就很容易的进行这种西历与和历的转换,而不需要写大量的代码进行和历的计算。

西历转和历函数示例1:格式(平成年月日)

1 StringBuilder strMsg = new StringBuilder();
2
3 strMsg.Append(System.Environment.NewLine + string.Format("{0:00:00}", 0100));
4 strMsg.Append(System.Environment.NewLine + string.Format("{0:#0:00}", 0100));
5
6 System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("ja-JP");
7 System.Globalization.Calendar cal = new System.Globalization.JapaneseCalendar();
8 ci.DateTimeFormat.Calendar = cal;
9 MessageBox.Show(DateTime.Parse("1990/09/06").ToString("ggy年M月d日", ci) + strMsg.ToString());

第9行中的日期格式还有多种

 1、ggy年M月d日
2、ggy年MM月d日

3、ggy年M月dd日

4、ggy年MM月dd日

原理很简单就不做解释了,不明白的同学可以自己测试一下就明白了。


西历转和历函数示例2:格式(H年月日)
1 System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("ja-JP");
2 System.Globalization.Calendar cal = new System.Globalization.JapaneseCalendar();
3 ci.DateTimeFormat.Calendar = cal;
4
5 DateTime dt = DateTime.Parse("2006/09/26");
6 Type t = typeof(System.Globalization.DateTimeFormatInfo);
7 System.Reflection.PropertyInfo pi = t.GetProperty("AbbreviatedEnglishEraNames", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
8
9  string[] engEras = (string[])pi.GetValue(ci.DateTimeFormat, null);
10 int era = cal.GetEra(dt);
11 string strWareki = engEras[era - 1] + dt.ToString("yy/MM/dd", ci);
12
13 MessageBox.Show(strWareki); // output: H18/09/26
posted @ 2011-06-22 14:29  meil  阅读(2956)  评论(0编辑  收藏  举报