DateTime.Compare (start, end) received on my system

enter image description here

In the above figure, you can see that the values startand are the endsame. but the comparison method returns -1, which means that the start time is less than the end time. How is this possible?

I tried sample values ​​in a console application to test the comapre method and how it works. I think there may be some kind of internal value of the object that datetimedoes not match. But could not 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;
}
+4
source share
4 answers

I offer a tolerance comparison, for example. millisecond shutdown:

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

, 127 . ! datetime , datetime ( milisecond 0). . , ?

. , . , , , .

:

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

, ( , ).

+2

MSDN

DateTime , , , , .

:

t1 t2, Ticks t1 t2, Kind. DateTime , .

: :

:

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

, .

+1

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

or even better with the 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 do not indicate that DateTime values ​​are immutable, so you are comparing two different DateTime values. the beginning and the end do not change and are still different. you can avoid this when trimming milliseconds during assignment

var start = DateTime.Now.TrimMilliseconds();
+1
source

Source: https://habr.com/ru/post/1617581/


All Articles