-
DateTime problem
Hi.
This is a bit of an issue I found.
My application has an object which has a property/field of a dateTime value.
On every tick, the current time is compared with the objects' datetime value and if it succeeds, it does a particular operation.
Now, thats fine when comparing TIME but when I want to compare the current Date/Time (DateTime.Now) - the condition never evaluates to true with the objects' datetime property :(
I can compare time, by specifiying each of the "time" values (Hour, Minute, Second) but I would like to be more efficient, and well generally better, and use the DateTime.Now to compare all factors, or at least the current date.
I have tried the DateTime.Equals() and the == operator but both seem to evaluate to false when that time approaches.
There is no code to show at all apart from comparing 2 objects:
Code:
if (DateTime.Now == ((SomeClass)this.TheCollection.TheStartTime)) {..}
-
Re: DateTime problem
Use >= instead, it's highly unlikely that Now() will ever return exactly the same as your intended time when you are calling it from a tick event. Timers can't be that accurate.
-
Re: DateTime problem
yeh i agree. but still - we are talking about the DATE not time and well, DATE will almost always remain constant throughout the Day :P
-
Re: DateTime problem
Code:
if (DateTime.Now.ToShortDateString == yourDate.ToShortDateString)
{
//code
}
-
Re: DateTime problem
The DateTime structure has a Date property that returns another DateTime object with the same date and the time zeroed to midnight, so if you want to compare your date to the current date you would use:
Code:
if (myDate.Date == DateTime.Today)
Note that DateTime.Today is like DateTime.Now but it too has the time zeroed to midnight, so DateTime.Today is the same as DateTime.Now.Date. The complement of DateTime.Date is DateTime.TimeOfDay, which returns a TimeSpan object that represents the time since midnight on that date.