I'm reading back a nullable datetime
using the IDataReader
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 Implementation_End_String
.
So this is what I tried. First Reading back the DateTime?
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 value
of the DateTime to call toString() on it.
Question:
How can I convert the read back DateTime?
value to a string type?
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.