繁体   English   中英

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

[英]How to manage parsing an null object for DateTime to be used with ADO.NET as 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。

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 */ }

您需要使用空的日期时间 - 快捷语法是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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM