Is there a way to combine these 2 methods for DateTime
(ignore the ticks while comparing datetimes) and TimeSpan
comparisons with generic parameter types and consolidating the logic?
private bool AreDateTimesEqual(DateTime? firstDateTime, DateTime? seconDateTime)
{
bool compareResult = false;
if (firstDateTime.HasValue && seconDateTime.HasValue)
{
firstDateTime = firstDateTime.Value.AddTicks(-firstDateTime.Value.Ticks);
seconDateTime = seconDateTime.Value.AddTicks(-seconDateTime.Value.Ticks);
compareResult = DateTime.Compare(firstDateTime.GetValueOrDefault(), seconDateTime.GetValueOrDefault()) == 0;
}
else if (!firstDateTime.HasValue && !seconDateTime.HasValue)
{
compareResult = true;
}
return compareResult;
}
private bool AreTimeSpansEqual(TimeSpan? firstTimeSpan, TimeSpan? secondTimeSpan)
{
bool compareResult = false;
if (firstTimeSpan.HasValue && secondTimeSpan.HasValue)
{
compareResult = TimeSpan.Compare(firstTimeSpan.GetValueOrDefault(), secondTimeSpan.GetValueOrDefault()) == 0;
}
else if (!firstTimeSpan.HasValue && !secondTimeSpan.HasValue)
{
compareResult = true;
}
return compareResult;
}
It sounds as if you're looking to compare two DateTime objects without the time part.
Keep in mind that both DateTime and TimeSpan implement the
IEquatable
interface which allows you to call Compare(...) on an instance of either.To compare dates without time:
For a DateTime variable, the .Date property will return the date without the time.
To compare TimeSpans, you would also use
.Compare
and check that the result is 0 (for equality).