Handling a DateTime DBNull

前端 未结 6 1918
广开言路
广开言路 2021-01-18 00:32

I have seen many, many versions of this on SO, but none of them seem to quite work for my needs.

My data comes from a vendor database that allows null for DateTime

6条回答
  •  花落未央
    2021-01-18 01:07

    here is an example of some code i use to read Datetimes

    im sure it could be written better but runs fine for me

       public DateTime? ReadNullableDateTimefromReader(string field, IDataRecord data)
        {
    
            var a = data[field];
            if (a != DBNull.Value)
            {
                return Convert.ToDateTime(a);
            }
            return null;
        }
    
        public DateTime ReadDateTimefromReader(string field, IDataRecord data)
        {
            DateTime value;
            var valueAsString = data[field].ToString();
            try
            {
                value = DateTime.Parse(valueAsString);
            }
            catch (Exception)
            {
                throw new Exception("Cannot read Datetime from reader");
            }
    
            return value;
        }
    

提交回复
热议问题