Abdur Rahim
Abdur Rahim

Reputation: 4021

DateTime.Compare(start, end) resulting weired in my system

enter image description here

In the above picture you can see that the start and end value is same. but the compare method is returning -1, which means start time is less than end time. How is this possible?

I have tried sample values in a console application to test comapre method, & its working fine. I think here may be some internal value of datetime object is not matching. But couldn't find.

Here is the code.

DateTime start = Convert.ToDateTime(pi.StartTime), end = Convert.ToDateTime(pi.EndTime);

int t1 = DateTime.Compare(start, end);

if (t1 == 0)
{
     MessageBox.Show("Start Time and End Time are same.");
     return;
}
else if (t1 == 1)
{
     MessageBox.Show("Start Time is greater then end time.");
     return;
}

Upvotes: 4

Views: 102

Answers (4)

Jürgen Steinblock
Jürgen Steinblock

Reputation: 31723

You can compare

DateTime.Compare(
    start.AddMilliseconds(-start.Millisecond), 
    end.AddMilliseconds(-end.Millisecond)
); 

or even better with an extension method

DateTime.Compare(start.TrimMilliseconds(), stop.TrimMilliseconds())

public static class DateTimeExtensions
{
    public static DateTime TrimMilliseconds(this DateTime date)
    {
        return date.AddMilliseconds(-date.Millisecond);
    }
}

please not that DateTime values are immutable so you are comparing two different DateTime values. start and end are not modified and are still differnt. you can avoid that with trimming the milliseconds during assignment

var start = DateTime.Now.TrimMilliseconds();

Upvotes: 1

jgauffin
jgauffin

Reputation: 101140

Just after the posting of Question, I checked each properties and found that there are difference of 127 miliseconds. WOW! And then I convert my system datetime to string and then again converting to datetime (as the milisecond become 0). so everything works fine now. So is it ok what I am doing?

No. By doing a conversion you do not communicate intent. The one reading your code will not understand why you did like that.

A much better way would be:

var difference = date1.Substract(date2).TotalSeconds;
return Math.Abs(difference) < 1;

Because then you show in the code that you accept a small difference (and how large difference you allow).

Upvotes: 2

AymenDaoudi
AymenDaoudi

Reputation: 8301

From MSDN

Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

Then it says :

To determine the relationship of t1 to t2, the Compare method compares the Ticks property of t1 and t2 but ignores their Kind property. Before comparing DateTime objects, ensure that the objects represent times in the same time zone.

And that s why you're having that result : here's an example :

Edit :

using System;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
        DateTime date2 = new DateTime(2009, 8, 1, 0, 0, 0);

        date2 = date2.AddMilliseconds(2);

        int result = DateTime.Compare(date1, date2);
        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}", date1, relationship, date2);
   }
}
// The example displays the following output:
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 AM

Hope that helped.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I suggest comparison with tolerance, e.g. trimming off milliseconds:

int t1 = DateTime.Compare(
  new DateTime(start.Ticks - (start.Ticks % TimeSpan.TicksPerSecond), start.Kind),
  new DateTime(end.Ticks - (end.Ticks % TimeSpan.TicksPerSecond), end.Kind));

Upvotes: 4

Related Questions