How to parse Nullable from a SqlDataReader

后端 未结 6 722
情歌与酒
情歌与酒 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 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);
        }
    }
    

提交回复
热议问题