Reputation: 6227
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?
Upvotes: 1
Views: 2370
Reputation: 205829
IDataReader
is a quite old interface, thus does not support natively nullable types. If you tend to use it at many places in your code, you'd better create some helpers which will significantly reduce your code. For instance, here are the helper methods for DateTime?
, you could easily do similar for the other types:
public static class DataReaderExtensions
{
public static DateTime? GetNullableDateTime(this IDataReader source, string name)
{
return source.GetNullableDateTime(source.GetOrdinal(name));
}
public static DateTime? GetNullableDateTime(this IDataReader source, int i)
{
return !source.IsDBNull(i) ? source.GetDateTime(i) : (DateTime?)null;
}
}
This, in combination with the C#6 null conditional operator would make the task in question simple as that:
Implementation_End_String = dataReader
.GetNullableDateTime("Implementation End Timestamp")?.ToString("d-MMMM-yyyy") ?? "";
Upvotes: 3
Reputation: 1180
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.
Upvotes: 3