How to parse Nullable<DateTime> from a SqlDataReader

14,057

Solution 1

How about this instead:

int x = reader.GetOrdinal("Placed");

if(!reader.IsDBNull(x))
    _placed = reader.GetDateTime(x);

Solution 2

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);

Solution 3

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);
    }
}

Solution 4

Use the IsDBNull method of the reader to determine if the value is null prior to trying to parse a date out of it.

Solution 5

DateTime? _placed  = null;
DateTime d2;
bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2);
if (isDate) _placed  = d2;
Share:
14,057
lowerkey
Author by

lowerkey

Front End Software Engineer at Knotis, Inc. Javascript Enthusiast.

Updated on June 16, 2022

Comments

  • lowerkey
    lowerkey about 2 years

    The DateTime.TryParse method takes a DateTime as an argument, not a DateTime? ?

    Right now I have the following code:

    if(!DateTime.TryParse(reader["Placed"].ToString(), out _placed)){
        throw new Exception("Order's placed datetime could not be parsed.");
    }
    

    where _placed is of type

    Nullable<DateTime> _placed = null;
    

    What's a way around that?

  • LukeH
    LukeH over 12 years
    +1. Or, if _placed needs to be assigned in either case: _placed = reader.IsDBNull(x) ? (DateTime?)null : reader.GetDateTime(x);
  • yzorg
    yzorg almost 10 years
    It's really a pity that in this age ADO doesn't have a built-in nullable DateTime helper.