I have this code below and the ‘if ((DateTime)DataReader[0] > DateTime.Now)’ condition returns false even if the datetime in the database is greater than the datetimenow.
I used this code before and it use to work I never changed any thing.
So the question is why does the condition return false?
Thanks,
Simon
Boolean active = false; SqlConnectionUniqueInstance.Instance.Open(); SqlCommand Command = SqlConnectionUniqueInstance.Instance.Connection.CreateCommand(); Command.CommandText = String.Format(@'SELECT [LogoutDateTime] FROM [dbo].[sessions] WHERE [sessionID] = {0}', sessionId.ToString()); SqlDataReader DataReader = Command.ExecuteReader(); while (DataReader.Read()) { if ((DateTime)DataReader[0] > DateTime.Now) active = true; } DataReader.Close(); if (active) UpdateTime(sessionId); Command.Dispose(); return active;
This is the actual answer:
You do not need/have/should to compare DateTime with >, <, == or != operators. Instead you can use the Compare and CompareTo methods of the DateTime class.
Compare: Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.
CompareTo: Overloaded. Compares the value of this instance to a specified DateTime value and indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.
http://msdn.microsoft.com/en-us/library/system.datetime_members.aspx