Friday, February 3, 2012

Comparing nullable dates

Sometimes working with Nullable<T> can be like arguing with a pedantic nerd.  And while being able to do this effectively is probably not something you want to advertise in the skills section of your résumé, you can win friends by translating for such challenged communicators.  Just as such, you can win programmer friends by writing extension methods that simplify overly verbose operations with... say... Nullable<DateTime>.

If you accept all that, then I present this here "friend catcher" to you.  Keep the anecdote close to heart that with great power comes great responsibility and always remember that you cannot hold me responsible if you crash Facebook with all the new friends you amass.  I will ignore any emails I receive blaming me so.

/// <summary>
/// Compares two nullable dates using only the day, month, and year.  
/// Ignores hours, minutes, seconds...
/// </summary>
public static int DateCompare(this DateTime? dt, DateTime? compareDate)
{
    DateTime? a = dt.HasValue ? dt.Value.Date as DateTime? : null;
    DateTime? b = compareDate.HasValue ? compareDate.Value.Date as DateTime? : null;
    return Nullable.Compare<DateTime>(a, b);
}

No comments: