Xerratus
Happily stressed out, since 1974


 
Tuesday, May 09, 2006
<< Movie Quote of the Day
Movie Quote of the Day >>

This morning we ran into a slight problem displaying data concerning null-able dates.  Let's say we have a table called "Foo" and Foo has 3 dates, 1 that can be null.  When we retrieve the data we call a routine that will retrieve the type of data we're expecting back.  For example, we know that "created", "modified", and "processed" are all date values so we know we can call GetDateValue(col) which will return a DateTime value.  In this routine, we basically use Convert.ToDateTime() to return the data.  Problem is that if variable col (the input parameter) is null the method returns "" because DateTime cannot be null.  This posed a problem viewing the data.

What I needed/wanted was a way to check the data to see if it was null but in a centralized place.  In no way, shape or form did I want 2 different programmers checking for a null date 2 different ways.  Problems arise that way because neither programmer knows how the other programmer is checking for null.  So I created a very quick, simple static function that I put in a generic class to check for a null date; IsDateNull(DateTime d) returns a boolean.
public static bool IsDateNull(DateTime d)
{
return d.Equals(Convert.ToDateTime(null));
}
Basically, we know that d was created using the Convert.ToDateTime() method and we know that when a null from the database is returned it calls Convert.ToDateTime(null).  So if we just simply compare the 2 we know if the date is null or not.  Also, if we returned new DateTime() instead of using the Convert.ToDateTime() method, "1/1/0001 12:00:00 AM" is still the default value returned.  So it will work for either scenario.  This minimizes the headache that I'd get if I was thumbing thru our code and saw something like this:
// On RowDataBound event
// Get control from data bound grid
Label l = (Label)e.FindControl("processedDateLabel");

if(l.Text == "1/1/0001 12:00:00 AM")
l.Text = "";
This would just aggravate me to no end.

Used properly and with a custom entity we can solve this problem via a property:
private DateTime _processedDate;
public string ProcessedDateDisplay
{
get
{
if(General.IsDateNull(_processedDate))
return "";
else return _processedDate.ToString();
}
}
When this entity is bound to a grid, processed date will display an empty column and NOT "1/1/0001 12:00:00 AM".

Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview