13

我有两个 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为 null 或 empty "",如果代码像这样运行,我会从 Parsing a empty string 得到 FormatException 错误。如何管理空解析并允许 DateTime(如果为空或 null)被接受为DBNull.Value

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

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

4

3 回答 3

19

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 */ }
于 2012-11-25T21:13:11.047 回答
4

您需要使用可为的日期时间 - 快捷语法是DateTime?(注意?末尾的)。

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

您可以测试hD.HasValue它是否不使用DbNull.Value

于 2012-11-25T21:09:49.260 回答
0

如果您使用此方法,任何不正确的日期都将返回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;
}
于 2012-11-25T21:38:42.497 回答