C# can't compare two datetimes properly

I'm new to C# and I'm trying to write a simple console application. I have two datetimes but I can't get the message Same, It keeps printing Different.

I also print the two datetimes in the console to know if they are different, but even when the system time is the same it doesn't satisfy the condition.

static void Main(string[] args)
{
    while (true)
    {
        Thread.Sleep(1000);
        DateTime dt1 = DateTime.Now;
        DateTime dt2 = DateTime.Parse("06:30:00 AM");

        if (TimeSpan.Compare(dt1.TimeOfDay, dt2.TimeOfDay) == 0)
        {
           Console.WriteLine("Same");
        }
        else
        {
           Console.WriteLine("Different");
        }

        Console.WriteLine(dt1);
        Console.WriteLine(dt2);
   }
}
Jon Skeet
people
quotationmark

DateTime has a resolution down to ticks, even though by default they're only printed to seconds in most cultures.

If you print dt1.ToString("o") and the same for dt2, you'll see that even if they're equal to the second, they may well vary in sub-second amounts. That explains why your current code can print "different" but then still print the same value for the next two lines.

people

See more on this question at Stackoverflow