Brian J Brian J - 1 year ago 92
C# Question

How to convert a nullable datetime value to string using data reader?

I'm reading back a

nullable datetime
using the
interface. So far my previous column reads are working as expected.

Except for this column
["Implementation End Timestamp"]
where I try to read back a nullable date time, convert it to string and assign it to a string property named

So this is what I tried. First Reading back the
value checking for null then attempting a convert toString() if not null.

But this assignment isn't allowed due to their being "no explicit conversion between string and DateTime?":

Implementation_End_String = dataReader["Implementation End Timestamp"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(dataReader["Implementation End Timestamp"]).ToString("d-MMMM-yyyy"), //show full month name

I think I need to get the
of the DateTime to call toString() on it.


How can I convert the read back
value to a string type?

Answer Source

Every Nullable<T> type has GetValueOrDefault method. You can use this method to retrieve value or default value of T (in your case it would be DateTime.MinValue) if there is no value. This method will return plain DateTime object so you can invoke any ToString() methods on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download