Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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;
}
like image 607
Abdur Rahim Avatar asked Feb 08 '23 11:02

Abdur Rahim


2 Answers

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));
like image 92
Dmitry Bychenko Avatar answered Feb 15 '23 11:02

Dmitry Bychenko


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

like image 37
jgauffin Avatar answered Feb 15 '23 11:02

jgauffin