C # newbie with DateTime variable I want to set to null
I have an output class with a DateTime variable. I want to clear this to zero in the loader class, but the compiler is complaining:
Cannot convert null to 'System.Data.Time' because it is a non-nullable value type.
As I understand it, but what if I change the type to DateTime? by creating a nullable wrapper, I get:
No overload for 'ToString' method takes arguments '1'
I have an output line that reads.
ACCOUNT_ESTABLISHED_DATE.ToString ("yyyy-MM-dd")
So the question is, when I set a DateTime to be nullable, how do I get around the fact that it no longer behaves like a DateTime that has a formatted ToString?
source to share
.NET doesn't have a method to do this. You need to have a helper method like:
public string Format(DateTime? date, string format)
{
if (date == null)
return string.Empty;
return date.Value.ToString(format);
}
Or even better, an extension method for DateTime?
:
public static class DateTimeExtensionMethods
{
public static string ToString(this DateTime? date, string format)
{
if (date == null)
return string.Empty;
return date.Value.ToString(format);
}
}
Then, to use your extension method, only use the code you have and make sure the namespace is DateTimeExtensionMethods
imported into your class.
source to share
You will need to use
dt.HasValue ? dt.Value.ToString("...") : dt.ToString();
This is because it Nullable<T>
is the correct type in its own right, the method is ToString()
already well executed as it handles the situation perfectly null
. But in order to navigate to the underlying nonzero object, you must use the property Value
. But then you will need to check null
(or HasValue
) yourself.
source to share
Have you looked at how to set DateTime to DataTime.MinValue?
Suggested here http://dotnetperls.com/datetime-null-minvalue
source to share