Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Nullable<DateTime> from a SqlDataReader

Tags:

c#

tsql

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?

like image 530
lowerkey Avatar asked Nov 08 '11 15:11

lowerkey


2 Answers

How about this instead:

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

if(!reader.IsDBNull(x))
    _placed = reader.GetDateTime(x);
like image 106
Dylan Meador Avatar answered Sep 20 '22 07:09

Dylan Meador


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);
like image 41
yzorg Avatar answered Sep 22 '22 07:09

yzorg