Partial DateTime Object Equality





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