Mr Moose
Mr Moose

Reputation: 6344

Comparing Date property of DateTime?

I am trying to work out a relatively clean way of comparing two types of DateTime? objects without having to bother with lots of null checking.

Is something like the following a good idea or is there a much simpler or sensible way to go about it;

DateTime? test = DateTime.MinValue;
DateTime? date1 = new DateTime(2008, 6, 1, 7, 47, 0);

if (string.Format("{0:MM/dd/yyyy}", date1) == string.Format("{0:MM/dd/yyyy}", test))
{
    Console.WriteLine("They are the same");
}
else
{
     Console.WriteLine("They are different");
}

Upvotes: 0

Views: 199

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500425

No, using text formatting to compare simple values is not a good idea IMO. One option to make things neater would be to write an extension method to effectively propagate nulls (like a maybe monad):

public static Nullable<TResult> Select<TSource, TResult>
    (this Nullable<TSource> input, Func<TSource, TResult> projection)
    where TSource : struct
    where TResult : struct
{
    return input == null ? (Nullable<TResult>) null : projection(input.Value);
}

You can then compare projections of nullable types easily:

if (date1.Select(x => x.Date).Equals(date2.Select(x => x.Date))

Or even add your own equality projection method:

public static bool EqualsBy<TSource, TResult>
    (this Nullable<TSource> x, Nullable<TSource> y,
     Func<TSource, TResult> projection)
    where TSource : struct
    where TResult : struct
{
    return x.Select(projection).Equals(y.Select(projection));
}

And:

if (date1.EqualsBy(date2, x => x.Date))

This is much more flexible and elegant than performing a text conversion when you really don't care about the text.

Upvotes: 5

Mohamed Ramadan
Mohamed Ramadan

Reputation: 803

Method1: to compare two dates values (after checking if it already have values)

if (test.HasValue && date1.HasValue 
    && test.Value.Date == date1.Value.Date)
{
// your code
}

Method2: to compare two dates using DateTime CompareTo function (after checking if it already have values)

if (test.HasValue && date1.HasValue 
    && date1.Value.Date.CompareTo(test.Value.Date) == 0)
{
// your code
}

Upvotes: 0

bvli
bvli

Reputation: 41

What's wrong with:

bool result = test == date1;

Edit: Sorry - didn't noticed you just wanted the date part.

bool result;
if (one.HasValue && two.HasValue) {
  result = one.Value.Date == two.Value.Date;
} else {
    result = one == two;
}

Upvotes: 2

Related Questions