Reputation: 17
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);
}
}
Upvotes: 1
Views: 193
Reputation: 5514
A DateTime
carries alot more precision than seconds, it is based on ticks, where each tick is 100 nanoseconds. So even if the DateTime.Now
matches in hours minutes and seconds, it will be way off in ticks.
You'd be better off using >
or <
when you attempt to compare. Or do (a - b) < some timespan
! Something like:
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Parse("06:30:00 AM");
bool matches = ( dt2 - dt1 ).Duration() < TimeSpan.FromMilliseconds( 100 ); // matches if dt1 and dt2 are within 0.1s
The .Duration()
call is needed to get an absolute time span that can't be negative. Note that you should never use this method for something like an alarm, your system could briefly freeze (due to a multitude of possibilites) and you'd miss it.
Upvotes: 2
Reputation: 223257
Your current comparison would compare Ticks for both DateTime
object. If you want to compare Hour, Minute and seconds then have a check like:
if (dt1.TimeOfDay.Hours == dt2.TimeOfDay.Hours &&
dt1.TimeOfDay.Minutes == dt2.TimeOfDay.Minutes &&
dt1.TimeOfDay.Seconds == dt2.TimeOfDay.Seconds)
Upvotes: 1
Reputation: 1500555
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.
Upvotes: 5