-1

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;
    }
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Steelbird
  • 49
  • 6
  • 3
    `firstDateTime.Value.AddTicks(-firstDateTime.Value.Ticks);` does that not just end up being 0? – leppie Nov 20 '14 at 05:34
  • No, it gives the firstDateTime value without the ticks and when assigned back to firstDateTime, it will override the value. – Steelbird Nov 20 '14 at 05:48
  • 1
    You do realize `Ticks` is not just a fractional part of a `DateTime`? It is the entire value! – leppie Nov 20 '14 at 05:50
  • I don't think you understand what the .Ticks property is. It is not the time. It is the total ticks from 12:00:00 midnight, January 1, 0001 until your DateTime. – dshapiro Nov 20 '14 at 05:52

1 Answers1

1

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

Maarten
  • 22,527
  • 3
  • 47
  • 68
dshapiro
  • 376
  • 2
  • 12