2017-02-27 29 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考虑使用可为空的日期时间(定义为“日期时间?”)。在某些情况下,这会更合适。