I have two dates and I only want to make sure they match on these 6 fields:
year, month, day, hour, minute and second.
I have noticed that if I perform a simple equality == comparison if(d1 == d2) that match on these fields, I still get ‘false’. I’m assuming this has to do with other fields under the hood that relate to ticks, milliseconds etc. How can I ignore everything and just make sure they match on the 6 fields above?
I have created the prototype function below but to me this feels amateurish and inefficient for production-level code. Furthermore, date1 has to be a nullable datetime.
Does anyone else have any better suggestions?
private static bool DatesAreEqual(DateTime date1, DateTime date2)
{
var d1 = new DateTime(date1.Year, date1.Month, date1.Day,
date1.Hour, date1.Minute, date1.Second);
var d2 = new DateTime(date2.Year, date2.Month, date2.Day,
date2.Hour, date2.Minute, date2.Second);
return d1 == d2;
}
3
Answers
This might be slightly quicker:
https://stackoverflow.com/a/58173628/759558
You can remove fractional part of the dates (please, note, that fractional part is longer then just milliseconds):
Code:
You can implement extension class to keep main code shorter and more readable:
And then
If you check on the TimeSpam, we have the
TimeSpan.TicksPerSecond
that is the minimum that you want to be the same (the seconds), so we reset that part to zero and we make the compare using ticks (that is the faster) as:With this way you just make some number compare and its the faster way.
More Than That
Base on the above code I also make two more functions with selected Precision and Equal, or Compare functions
Simple Visual Test
output