How to manage parsing an null object for DateTime to be used with ADO.NET as DBNULL

笑着哭i 提交于 2019-12-05 01:37:49

You need to use nullable date times - the shortcut syntax would be DateTime? (note the ? at the end).

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

You can test for hD.HasValue and if it doesn't use DbNull.Value instead.

The Parse method can't handle empty strings, but you can use nullable DateTime and do something like this:

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

But even safer would be using TryParse instead:

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

Then for storing this value, you can test hD.HasValue:

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

Since C# 7, you can use shorter syntax for inline out parameters and you can avoid nullable type altogether:

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

If you use this method, any thing that is not a correct date will return a 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!