Is there a way to combine these 2 methods for DateTime and TimeSpan comparisons

223 views Asked by At

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;
    }
1

There are 1 answers

3
dshapiro On

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:

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddHours(5);
return date1.Date.Compare(date2.Date) == 0;

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).