1. 程式人生 > >C# string轉換成DateTime?(字串轉換成可空日期型別)

C# string轉換成DateTime?(字串轉換成可空日期型別)

最近專案中遇到以前一直困擾的問題,就是如何將string轉換成DateTime?這種可空日期型別。以前總是通過編寫一堆邏輯程式碼來進行轉換,但是寫這些程式碼感覺非常繁瑣。後在網上瀏覽相關資料,使用NullableConverter類就可以輕鬆的進行轉換。

以下是測試的部分程式碼,程式碼在控制檯應用程式中執行:

/* 測試string型別轉換成DateTime?型別*/ 
/*NullableConverter類建構函式必須傳入要轉換的型別*/

System.ComponentModel.NullableConverter nullableDateTime = new System.ComponentModel.NullableConverter(typeof(DateTime?));

/*
*正常日期格式字串轉換為DateTime?
*/
string strDate = DateTime.Now.ToString();
DateTime? dt1=(DateTime?)nullableDateTime.ConvertFromString(strDate);
Console.WriteLine("正常日期格式字串轉換成DateTime?:{0}", dt1);

/*
*字串為空白轉換為DateTime?
*/
strDate = string.Empty;
DateTime? dt2 = (DateTime?)nullableDateTime.ConvertFromString(strDate);
Console.WriteLine("空白字串轉換成DateTime?:{0}", dt2);

/*
*字串為NULL轉換為DateTime?
*/
strDate = null;
DateTime? dt3 = (DateTime?)nullableDateTime.ConvertFromString(strDate);
Console.WriteLine("NULL字串轉換成DateTime?:{0}", dt3); 
Console.Read();

輸出的結果是:字串轉換可控日期型別結果圖

總結果上看可以順利將空字串和正常的字串轉換成DateTime?型別,但是如果傳入非法的日期格式的字串會報錯,需要另外處理。