如何管理解析DateTime的空对象以与ADO.NET一起用作DBNULL

我有两个DateTime对象,BirthDate和HireDate。 它们被正确格式化为字符串,当我将它们传递给我的数据访问层时,需要将它们解析为DateTime对象。

DateTime hD = DateTime.Parse(hire); DateTime bD = DateTime.Parse(birth); //incase of a datestring being passed through dateStringPassed = "7/2/1969"; 

但有时候,字符串hirebirth是空的或空的"" ,如果代码是这样运行的,我从解析空字符串得到一个FormatException错误。 如何管理空分析并允许DateTime(如果为空或null)被接受为DBNull.Value

我仍然无法管理用户没有通过DateTime字符串,然后解析崩溃了我的代码。

我的出生日期参数如下,如果为null则检查变量,然后使用DBNull.Value。

您需要使用可为空的日期时间 – 快捷语法是DateTime? (注意最后的? )。

 DateTime? hD = null; if(!string.IsNullOrWhitespace(hire )) // string.IsNullOrEmpty if on .NET pre 4.0 { hD = DateTime.Parse(hire); } 

您可以测试hD.HasValue ,如果它不使用DbNull.Value

Parse方法无法处理空字符串,但您可以使用可为空的DateTime并执行以下操作:

 DateTime? hD = String.IsNullOrEmpty(hire) ? (DateTime?)null : DateTime.Parse(hire) 

但更安全的是使用TryParse

 DateTime? hD = null; DateTime.TryParse(hire, out hD); 

然后,为了存储该值,您可以测试hD.HasValue

 if(hD.HasValue) { /* use hD */ } else { /* else use DBNull.Value */ } 

从C#7开始,您可以使用更短的语法来内联输出参数,并且可以完全避免使用可空类型:

 if (DateTime.TryParse(hire, out var hD)) { /* use hD */ } else { /* use DBNull.Value */ } 

如果您使用此方法,任何不正确的日期将返回DBNull.Value

 ///  /// Parses a date string and returns /// a DateTime if it is a valid date, /// if not returns DBNull.Value ///  /// Date string /// DateTime or DBNull.Value public static object CreateDBDateTime(string date) { DateTime result; if (DateTime.TryParse(date, out result)) { return result; } return DBNull.Value; }