65.9K
CodeProject is changing. Read more.
Home

Partial DateTime Object Equality

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Oct 9, 2011

CPOL
viewsIcon

5060

This is an alternative to "Partial DateTime Object Equality".

I don't mind multiple exits in such a simple method, hence I'd write:

public static bool Equals(this DateTime now, DateTime then, DatePartFlags flags) {
    if ((flags & DatePartFlags.Ticks) != 0 && now.Ticks != then.Ticks) return false;
    ...
    if ((flags & DatePartFlags.Month) != 0 && now.Month != then.Month) return false;
    if ((flags & DatePartFlags.Year) != 0 && now.Year != then.Year) return false;
    return true;
}

Some remarks:

  1. This offers short-circuiting.
  2. You might want to reorder the test statements if bigger DT parts are more relevant in your world.
  3. I changed the method name to conform to .NET conventions.
  4. I assume a non-zero DatePartFlags.Ticks value, which makes more sense to me.
  5. I object to the original FlagIsSet() method: it is confusing when the second parameter does not have exactly one bit set.