Partial DateTime Object Equality
This is an alternative for "Partial DateTime Object Equality"
Introduction
I was messing around with some code that used this tip, and came up with an alternative.
Using the code
We still compare the flags, but instead of creating a new flag
variable, we create a string
, convert it to a 64-bit integer, and compare the resulting integers for the dates in question. I'm sure this isn't as efficient, but it is another way to look at it.
public static bool PartiallyEqual2
(this DateTime then, DateTime now, DatePartFlags flags = DatePartFlags.Ticks)
{
bool isEqual = false;
if (flags == DatePartFlags.Ticks)
{
isEqual = (now == then);
}
else
{
StringBuilder compareStr = new StringBuilder();
compareStr.Append(flags.HasFlag(DatePartFlags.Year) ?"yyyy":"");
compareStr.Append(flags.HasFlag(DatePartFlags.Month) ?"MM":"");
compareStr.Append(flags.HasFlag(DatePartFlags.Day) ?"dd":"");
compareStr.Append(flags.HasFlag(DatePartFlags.Hour) ?"HH":"");
compareStr.Append(flags.HasFlag(DatePartFlags.Minute) ?"mm":"");
compareStr.Append(flags.HasFlag(DatePartFlags.Second) ?"ss":"");
compareStr.Append(flags.HasFlag(DatePartFlags.Millisecond)?"fff":"");
isEqual = now.ConvertToInt64
(compareStr.ToString()) == then.ConvertToInt64(compareStr.ToString());
}
return isEqual;
}
public static Int64 ConvertToInt64(this DateTime thisDate, string format)
{
Int64 dateValue = Convert.ToInt64(thisDate.ToString(format));
return dateValue;
}
History
- 6th February, 2015: Initial version