qasimalbaqali
qasimalbaqali

Reputation: 2131

DateTime.Compare doesn't work as expected

I'm trying to compare two DateTime objects ignoring the seconds with the below function, but it gives the wrong result even though both of the DateTime objects are have the same values. Can't figure out how to exactly get it working, any help would be highly appreciated.

public static int CompareDateTime(DateTime d1, DateTime d2)
{
    d1 = d1.AddSeconds(-1 * d1.Second);
    d2 = d2.AddSeconds(-1 * d2.Second);

    int result = DateTime.Compare(d1, d2);
    string relationship;

    if (result < 0)
        relationship = "is earlier than";
    else if (result == 0)
        relationship = "is the same time as";
    else
        relationship = "is later than";

    Console.WriteLine("{0} {1} {2}", d1, relationship, d2);

    return result;

}

Result:

3/7/2017 2:54:00 PM is later than 3/7/2017 2:54:00 PM

Upvotes: 2

Views: 5589

Answers (3)

xanatos
xanatos

Reputation: 111940

Everyone is giving a solution for truncating time... So I'll give the one that I normally use... A DateTime is the number of ticks starting from 0:00:00 on January 1, 0001... so if you know how many ticks there are in a minute (there is a readonly field for that: TimeSpan.TicksPerMinute) you can count the number of minutes from January 1, 0001...

long minutes1 = d1.Ticks / TimeSpan.TicksPerMinute;
long minutes2 = d2.Ticks / TimeSpan.TicksPerMinute;

int result = minutes1.CompareTo(minutes2);

(note that there are various "useful" values in TimeSpan: TicksPerDay, TicksPerHour, TicksPerMinute, TicksPerSecond, TicksPerMillisecond)

Upvotes: 3

Innat3
Innat3

Reputation: 3576

You just need to ignore the milliseconds as well. You could add this to your code, or go for the more 'elegant' solution suggested by @Chris

d1 = d1.AddMilliseconds(-1 * d1.Millisecond);
d2 = d2.AddMilliseconds(-1 * d2.Millisecond);

Upvotes: 3

Chris
Chris

Reputation: 27627

The problem here is that you aren't truncating as you expect to. The best way to truncate is to create an entirely new DateTime object from the constructor by doing the following:

d1 = new DateTime(d1.Year, d1.Month, d1.Day, d1.Hour, d1.Minute, 0);
d2 = new DateTime(d2.Year, d2.Month, d2.Day, d2.Hour, d2.Minute, 0);

This will ensure you are only comparing the data you want.

In this specific case it is the milliseconds that may have been part of the datetime that were being left by your attempted truncation.

Upvotes: 8

Related Questions