我有两个日期时间对象,BirthDate和HireDate。它们被正确格式化为字符串,当我将它们传递到数据访问层时,需要将它们解析为 DateTime 对象。
DateTime hD = DateTime.Parse(hire);
DateTime bD = DateTime.Parse(birth);
//incase of a datestring being passed through
dateStringPassed = "7/2/1969";
但有时,字符串hire
和birth
为空或空""
,如果代码像这样运行,我会从解析空字符串时收到 FormatException 错误。如何管理空解析并允许 DateTime(如果为空或 null)被接受为DBNull.Value
?
我仍然无法管理,以防用户不传递 DateTime 字符串,然后解析使我的代码崩溃。
我的出生日期参数如下,如果为空,则检查变量,然后使用 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 开始,可以对内联输出参数使用较短的语法,并且可以完全避免可为 null 的类型:
if (DateTime.TryParse(hire, out var hD)) { /* use hD */ }
else { /* use 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
。
如果使用此方法,任何日期不正确的内容都将返回DBNull.Value
:
/// <summary>
/// Parses a date string and returns
/// a DateTime if it is a valid date,
/// if not returns DBNull.Value
/// </summary>
/// <param name="date">Date string</param>
/// <returns>DateTime or DBNull.Value</returns>
public static object CreateDBDateTime(string date)
{
DateTime result;
if (DateTime.TryParse(date, out result))
{
return result;
}
return DBNull.Value;
}