Partial DateTime Object Equality





5.00/5 (1 vote)
This is an alternative for "Partial DateTime Object Equality"
Introduction
I herein refer to the original post of http://www.codeproject.com/Tips/148065/Partial-DateTime-Object-Equality and offer some alterantive approch.
You may employ more of the native C# support for this partial DateTime Equality function:
- Define the enum flags with bit shift operator instead of manually calculated powers of two values
- Use Enum.HasFlag() on the mask instead of a self-invented function.
- Use boolean logic to directly calculate the boolean result instead of over the re-calculation of some flag values.
Using the code
Alternative definition of the Equality Mask:
Use bit-shift instead of hardcoded values.
Original | Alternative |
---|---|
[Flags]
public enum DatePartFlags
{
Ticks=0,
Year=1,
Month=2,
Day=4,
Hour=8,
Minute=16,
Second=32,
Millisecond=64
}; |
[Flags]
public enum DtMask
{
// make conformant to MS guidelines again:
// define a meaningful 0-value
Ticks = 0,
Year = (1<<0),
Month = (1<<1),
Day = (1<<2),
Hour = (1<<3),
Minute = (1<<4),
Second = (1<<5),
Millisecond = (1<<6),
Full = Ticks,
Date = Day|Month|Year,
Time = Hour|Minute|Second|Millisecond,
};
|
An alternative Equals method:
Use the HasFlag() method that is defined on all enum types.
In addition, you might use the direct logic that allows for shortcut evaluation for the first failure (usage of && and ||).
public static bool Equal(this DateTime now, DateTime then, DtMask mask)
{
// Caution: 0-value always match in HasFlag(), use therefore "=="
return mask == DtMask.Full ? now == then
: (!mask.HasFlag(DtMask.Millisecond) || now.Millisecond == then.Millisecond)
&& (!mask.HasFlag(DtMask.Second) || now.Second == then.Second)
&& (!mask.HasFlag(DtMask.Minute) || now.Minute == then.Minute)
&& (!mask.HasFlag(DtMask.Hour) || now.Hour == then.Hour)
&& (!mask.HasFlag(DtMask.Day) || now.Day == then.Day)
&& (!mask.HasFlag(DtMask.Month) || now.Month == then.Month)
&& (!mask.HasFlag(DtMask.Year) || now.Year == then.Year);
}
History
1.0 | Initial version |
1.1 | added more refrences to the original post |
1.2 | Adjusted enum and Equals method by taking Jani's input into count: Full == Ticks, take Milliseconds into Time check |