How to parse Nullable from a SqlDataReader

后端 未结 6 719
情歌与酒
情歌与酒 2021-01-17 17:37

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

Right now I have the following code:

if(!DateTime.TryParse(reader[\"P         


        
相关标签:
6条回答
  • 2021-01-17 17:48

    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);
    
    0 讨论(0)
  • 2021-01-17 17:54

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

    0 讨论(0)
  • 2021-01-17 17:55

    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.

    0 讨论(0)
  • 2021-01-17 17:57

    How about this instead:

    int x = reader.GetOrdinal("Placed");
    
    if(!reader.IsDBNull(x))
        _placed = reader.GetDateTime(x);
    
    0 讨论(0)
  • 2021-01-17 18:05
    DateTime? _placed  = null;
    DateTime d2;
    bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2);
    if (isDate) _placed  = d2;
    
    0 讨论(0)
  • 2021-01-17 18:07

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题