lowerkey
lowerkey

Reputation: 8345

How to parse Nullable<DateTime> from a SqlDataReader

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?

Upvotes: 11

Views: 15072

Answers (6)

brendanrichards
brendanrichards

Reputation: 329

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

Upvotes: 5

yzorg
yzorg

Reputation: 4480

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

Upvotes: 7

Jim H.
Jim H.

Reputation: 5579

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

Upvotes: 1

Dylan Meador
Dylan Meador

Reputation: 2401

How about this instead:

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

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

Upvotes: 22

Kinexus
Kinexus

Reputation: 12904

DateTime? _placed  = null;
DateTime d2;
bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2);
if (isDate) _placed  = d2;

Upvotes: 1

Iesvs
Iesvs

Reputation: 125

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.

Upvotes: 0

Related Questions