How to parse Nullable <DateTime> from SqlDataReader

Does the DateTime.TryParse method accept DateTime as an argument, not a DateTime?

Now I have the following code:

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

where _placed is of type

 Nullable<DateTime> _placed = null; 

How to do it?

+8
c # tsql
source share
6 answers

How about this:

 int x = reader.GetOrdinal("Placed"); if(!reader.IsDBNull(x)) _placed = reader.GetDateTime(x); 
+19
source share

Just a combination of top response and top comment. Thanks @ Dylan-Meador and @LukeH.
(Note: for a long tail, I think this version will save many human times.)

 int x = reader.GetOrdinal("Placed"); DateTime? _placed = reader.IsDBNull(x) ? (DateTime?)null : reader.GetDateTime(x); 
+6
source share

So @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); } } 
+2
source share
 DateTime? _placed = null; DateTime d2; bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2); if (isDate) _placed = d2; 
+1
source share

Use the IsDBNull read method to determine if it is null before attempting to parse a date from it.

+1
source share

This is normal. Out is not set if parsing is not performed. Therefore, if the type of wargame was Nullable, it would be redudant information.

0
source share

All Articles