同事問到,如何將 "中華民國97年2月29日" 的字串轉成 DateTime, 與將 DateTime 輸出成 "中華民國97年2月29日"
沒遇過這個問題。
打開 MSDN, 找到了 TaiwanCalendar
開始寫程式囉
DateTime dt = new DateTime(2008, 2, 29);
TaiwanCalendar c = new TaiwanCalendar();
CultureInfo ci = new CultureInfo("zh-TW", true);
ci.DateTimeFormat.Calendar = c;
Thread.CurrentThread.CurrentCulture = ci;
Console.WriteLine(dt.ToLongDateString());
DateTime dt2;
dt2 = DateTime.Parse("97-02-29", ci);
Console.WriteLine(dt2.ToLongDateString());
dt2 = DateTime.Parse("97/02/29", ci);
Console.WriteLine(dt2.ToLongDateString());
dt2 = DateTime.Parse("97-2-29", ci);
Console.WriteLine(dt2.ToLongDateString());
dt2 = DateTime.ParseExact("97|02|29", "yy|MM|dd", ci);
Console.WriteLine(dt2.ToLongDateString());
dt2 = DateTime.ParseExact("中華民國97年2月29日", "中華民國yy年M月dd日", ci);
Console.WriteLine(dt2.ToLongDateString());
dt2 = DateTime.ParseExact("中華民國97年2月29日", "中華民國yy年M月dd日", ci);
Console.WriteLine(dt2.ToLongDateString());
dt2 = DateTime.Parse("97/02/29 下午 3:46:01");
Console.WriteLine(dt2.ToString());
輸出的結果如下
97年2月29日
97年2月29日
97年2月29日
97年2月29日
97年2月29日
97年2月29日
sample code download here
沒有留言:
張貼留言