Given the nature of a date/time data type it cannot contain a null
value, i.e. it needs to contain a value, it cannot be blank or contain nothing. If you mark a date/time variable as nullable
then only can you assign a null value to it. So what you are looking to do is one of two things (there might be more but I can only think of two):
Assign a minimum date/time value to your variable if you don't have a value for it. You can assign a maximum date/time value as well - whichever way suits you. Just make sure that you are consistent site-wide when checking your date/time values. Decide on using min
or max
and stick with it.
Mark your date/time variable as nullable
. This way you can set your date/time variable to null
if you don't have a variable to it.
Let me demonstrate my first point using an example. The DateTime
variable type cannot be set to null, it needs a value, in this case I am going to set it to the DateTime
's minimum value if there is no value.
My scenario is that I have a BlogPost
class. It has many different fields/properties but I chose only to use two for this example. DatePublished
is when the post was published to the website and has to contain a date/time value. DateModified
is when a post is modified, so it doesn't have to contain a value, but can contain a value.
public class BlogPost : Entity
{
public DateTime DateModified { get; set; }
public DateTime DatePublished { get; set; }
}
Using ADO.NET
to get the data from the database (assign DateTime.MinValue
is there is no value):
BlogPost blogPost = new BlogPost();
blogPost.DateModified = sqlDataReader.IsDBNull(0) ? DateTime.MinValue : sqlDataReader.GetFieldValue<DateTime>(0);
blogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);
You can accomplish my second point by marking the DateModified
field as nullable
. Now you can set it to null
if there is no value for it:
public DateTime? DateModified { get; set; }
Using ADO.NET
to get the data from the database, it will look a bit different to the way it was done above (assigning null
instead of DateTime.MinValue
):
BlogPost blogPost = new BlogPost();
blogPost.DateModified = sqlDataReader.IsDBNull(0) ? (DateTime?)null : sqlDataReader.GetFieldValue<DateTime>(0);
blogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);
I hope this helps to clear up any confusion. Given that my response is about 8 years later you are probably an expert C# programmer by now :)