2017-02-27 21 views
1

當我使用一個空字符串作爲DateTime.Parse參數,關閉所有窗口後,該應用程序仍在運行,像這樣:解析一個空字符串爲DateTime使得應用程序不能關閉

txtBirthDate.SelectedDate = ("" == empBirthDate) ? DateTime.Parse("") : DateTime.Parse(empBirthDate); 

但是,當我進入迄今爲止,例如像11/26/1995,應用程序停止運行後,我關閉了所有的窗口:

txtBirthDate.SelectedDate = ("" == empBirthDate) ? DateTime.Parse("11/26/1995") : DateTime.Parse(empBirthDate); 

這是對DateTime.Parse的一個特徵,或者是別的什麼?

+0

首先,'DateTime.Parse(「」)'拋出一個'FormatException',爲什麼你會故意拋出一個異常呢? – mok

+0

我認爲對此有一點背景會有很大幫助。也不信任輸入是默認情況下的一個好主意。我會調查使用'DateTime.TryParse'來檢查輸入 - 可能有幫助。 – Gabe

+0

@mok我不知道,但是在將代碼放入try-catch後出現錯誤,可能這就是爲什麼在關閉所有窗口後應用程序沒有停止運行的原因。如果有一個空白字符串是不可能的,當'empBirthDate'沒有值時我該怎麼辦? – Swellar

回答

0

DateTime.Parse不能解析空字符串,相反,如果輸入字符串爲空或空,則可以返回DateTime.MinValue或返回DateTime.Today。在這種情況下,代碼將是這樣的:

txtBirthDate.SelectedDate = String.IsNullOrEmpty(empBirthDate) ? 
            DateTime.MinValue : 
            DateTime.Parse(empBirthDate); 

如果你知道有關日期的變量empBirthDate格式則成了TryParseExact更容易,在這種情況下,inDate變量的值將是DateTime.MinValue如果轉換失敗,或者它將具有正確的值。所以你可以嘗試這樣的:

DateTime inDate; 
string currentFormat = "MM/dd/yyyy"; 
DateTime.TryParseExact(empBirthDate, currentFormat , CultureInfo.InvariantCulture, DateTimeStyles.None, out inDate); 
txtBirthDate.SelectedDate = inDate; 
+0

這很好。只是好奇,是'String.IsNullOrEmpty(empBirthDate)'比'「」== empBirthDate'好? – Swellar

+1

是的,它比'=='比較好 –

0

基本上不幸運是正確的。但是第一個代碼示例在輸入無效的情況下仍然會拋出異常。雖然第二實施例具有以下面的方式來進行修改:

DateTime inDate; 
string currentFormat = "MM/dd/yyyy"; 
if (DateTime.TryParseExact(empBirthDate, currentFormat , CultureInfo.InvariantCulture, DateTimeStyles.None, out inDate)) 
{ 
    txtBirthDate.SelectedDate = inDate; 
} 

此外代替使用DateTime.MinValue考慮使用可爲空的日期時間(定義爲「日期時間?」)。在某些情況下,這會更合適。