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;
}
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));
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With