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 |
---|
1 [Flags]
2 public enum DatePartFlags
3 {
4
5
6 Ticks=0,
7 Year=1,
8 Month=2,
9 Day=4,
10 Hour=8,
11 Minute=16,
12 Second=32,
13 Millisecond=64
14 };
|
1 [Flags]
2 public enum DtMask
3 {
4
5
6 Ticks = 0,
7 Year = (1<<0),
8 Month = (1<<1),
9 Day = (1<<2),
10 Hour = (1<<3),
11 Minute = (1<<4),
12 Second = (1<<5),
13 Millisecond = (1<<6),
14
15 Full = Ticks,
16 Date = Day|Month|Year,
17 Time = Hour|Minute|Second|Millisecond,
18 };
|
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 ||).
1 public static bool Equal(this DateTime now, DateTime then, DtMask mask)
2 {
3
4 return mask == DtMask.Full ? now == then
5 : (!mask.HasFlag(DtMask.Millisecond) || now.Millisecond == then.Millisecond)
6 && (!mask.HasFlag(DtMask.Second) || now.Second == then.Second)
7 && (!mask.HasFlag(DtMask.Minute) || now.Minute == then.Minute)
8 && (!mask.HasFlag(DtMask.Hour) || now.Hour == then.Hour)
9 && (!mask.HasFlag(DtMask.Day) || now.Day == then.Day)
10 && (!mask.HasFlag(DtMask.Month) || now.Month == then.Month)
11 && (!mask.HasFlag(DtMask.Year) || now.Year == then.Year);
12 }
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 |