Reputation: 813
Im trying to compare if a runtime variable is within now and one minute from now. Here is the code:
if (RunTime.ToUniversalTime() >= now.ToUniversalTime() &&
RunTime.ToUniversalTime() < now.AddMinutes(1).ToUniversalTime())
{
//Do Stuff
}
However this evaluates to true a minute before I would expect. for instance if I have my runtime as 9:30 it evaluates to true from 9:29 to 9:30 not 9:30 - 9:31. What Am I missing here? The way I understand the code is that it would evaluate to true when runtime is greater than or equal to now and less than now plus one minute.
Upvotes: 1
Views: 144
Reputation: 26
I like to use type TimeSpan when doing date-time comparisons.
TimeSpan timeSpan = Runtime.ToUniversalTime().Subtract(now.ToUniversalTime());
if (timeSpan > 0 && timeSpan <= 1)
{
//Code here
}
Upvotes: 0
Reputation: 22122
RunTime.ToUniversalTime() >= now.ToUniversalTime() &&
RunTime.ToUniversalTime() < now.AddMinutes(1).ToUniversalTime()
Let us rewrite this condition:
now.ToUniversalTime() <= RunTime.ToUniversalTime() &&
now.ToUniversalTime() > RunTime.AddMinutes(-1).ToUniversalTime()
So when RunTime
is 9:30, then condition should be true from RunTime.AddMinutes(-1)
(9:29) exclusive to RunTime
(9:30) inclusive. Just like you say it is in your post.
If you what that condition be true from 9:30 to 9:31, than you should use different condition:
now.ToUniversalTime() >= RunTime.ToUniversalTime() &&
now.ToUniversalTime() < RunTime.AddMinutes(1).ToUniversalTime()
Upvotes: 3
Reputation: 109567
The following code works as expected (i.e it prints "Second true" and not "First true"):
DateTime nine29 = new DateTime(2015, 01, 01, 09, 29, 00);
DateTime nine30 = new DateTime(2015, 01, 01, 09, 30, 00);
DateTime runtime = nine30;
if (runtime.ToUniversalTime() >= nine29.ToUniversalTime() && runtime.ToUniversalTime() < nine29.AddMinutes(1).ToUniversalTime())
Console.WriteLine("First true");
if (runtime.ToUniversalTime() >= nine30.ToUniversalTime() && runtime.ToUniversalTime() < nine30.AddMinutes(1).ToUniversalTime())
Console.WriteLine("Second true");
Therefore we must assume that you are mistaken when you say "if I have my runtime as 9:30 it evaluates to true from 9:29 to 9:30 not 9:30 - 9:31."
Put all your times into variables and print them out to the debug window or the console, or run it under the debugger and inspect them. And pay attention to the seconds!
Upvotes: 1
Reputation: 331
Since you're using DateTime.Now
you're never going to land precisely on the exact same time. Consider these two cases:
Case 1 (what you're experiencing)
now: 9:29:01
runtime: 9:30:00
now+1: 9:30:01
Case 2 (what you want but doesn't work)
now: 9:30:01
runtime: 9:30:00
now+1: 9:31:01
Try setting your now variable explicitly and make some logical tables of what should happen. You will get better insight to the rule you want to create.
Upvotes: 2