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
lowerkey
source share6 answers
How about this:
int x = reader.GetOrdinal("Placed"); if(!reader.IsDBNull(x)) _placed = reader.GetDateTime(x); +19
Dylan meador
source shareJust 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
yzorg
source shareSo @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
brendanrichards
source share DateTime? _placed = null; DateTime d2; bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2); if (isDate) _placed = d2; +1
Chrisbint
source shareUse the IsDBNull read method to determine if it is null before attempting to parse a date from it.
+1
Jim H.
source shareThis 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
Isvs
source share