How can I convert the nullable DateTime dt2 to a formatted string?
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(\"yyyy-MM-dd hh
Here is a more generic approach. This will allow you to string format any nullable value type. I have included the second method to allow overriding the default string value instead of using the default value for the value type.
public static class ExtensionMethods
{
public static string ToString<T>(this Nullable<T> nullable, string format) where T : struct
{
return String.Format("{0:" + format + "}", nullable.GetValueOrDefault());
}
public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue) where T : struct
{
if (nullable.HasValue) {
return String.Format("{0:" + format + "}", nullable.Value);
}
return defaultValue;
}
}
I like this option:
Console.WriteLine(dt2?.ToString("yyyy-MM-dd hh:mm:ss") ?? "n/a");