Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Compare doesn't work as expected

Tags:

c#

.net

datetime

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
like image 517
qasimalbaqali Avatar asked May 02 '26 09:05

qasimalbaqali


1 Answers

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.

like image 112
Chris Avatar answered May 04 '26 23:05

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!