当我在DateTime.Parse
中使用空字符串作为参数时,关闭所有窗口后,应用程序仍在运行,如下所示:
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 :(得分:0)
DateTime.Parse
无法解析空字符串,相反,如果输入字符串为null或Empty,则可以返回DateTime.MinValue
或DateTime.Today
。在这种情况下,代码将是这样的:
txtBirthDate.SelectedDate = String.IsNullOrEmpty(empBirthDate) ?
DateTime.MinValue :
DateTime.Parse(empBirthDate);
如果您了解变量empBirthDate
中的日期格式,那么使用TryParseExact
会更容易,在这种情况下,inDate
变量的值将为{{1如果转换失败,或者它将具有正确的值。所以你可以尝试这样:
DateTime.MinValue
答案 1 :(得分:0)
基本上不幸运是对的。但是第一个代码示例仍会在输入无效的情况下抛出异常。虽然必须按以下方式修改第二个示例:
DateTime inDate;
string currentFormat = "MM/dd/yyyy";
if (DateTime.TryParseExact(empBirthDate, currentFormat , CultureInfo.InvariantCulture, DateTimeStyles.None, out inDate))
{
txtBirthDate.SelectedDate = inDate;
}
还考虑使用可以为空的DateTime(定义为'DateTime?')而不是使用DateTime.MinValue。在某些情况下,这更合适。