The DateTime.TryParse method takes a DateTime as an argument, not a DateTime? ?
Right now I have the following code:
if(!DateTime.TryParse(reader[\"P
Just a combination of top answer and top comment. Thanks @Dylan-Meador and @LukeH.
(Ed. Note: For the long tail I think this version will save plenty of human time.)
int x = reader.GetOrdinal("Placed");
DateTime? _placed = reader.IsDBNull(x) ? (DateTime?)null : reader.GetDateTime(x);
Use the IsDBNull
method of the reader to determine if the value is null prior to trying to parse a date out of it.
It's normal. The out argument is not set if the parse fail. So if the type of the wargument were Nullable it would have been a redudant information.
How about this instead:
int x = reader.GetOrdinal("Placed");
if(!reader.IsDBNull(x))
_placed = reader.GetDateTime(x);
DateTime? _placed = null;
DateTime d2;
bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2);
if (isDate) _placed = d2;
And here is @yzorg 's answer turned into a reusable extension method
public static class SqlDataReaderExtensions
{
public static DateTime? GetNullableDateTime(this SqlDataReader reader, string fieldName)
{
int x = reader.GetOrdinal(fieldName);
return reader.IsDBNull(x) ? (DateTime?) null : reader.GetDateTime(x);
}
}