C#, SQL and the DateTime object...

  • Thread starter Thread starter Matthias S.
  • Start date Start date
M

Matthias S.

Hi,

I create a DateTime object in C# like this...

DateTime _DateStart = new DateTime(2000, 1, 1, 1, 1, 1, 1);

Now I save it to the Database (into a DateTime type of column) using the
SqlCommand and later I reload the value. Comparing those using the == operator
of the DateTime object yields incorrect results. Say I have two DateTime
objects, one was loaded from the DB:

DateTime _DateLoaded = LoadTheDateFromTheDB();
DateTime _DateToCompareWith = new DateTime(2000, 1, 1, 1, 1, 1, 1);

if (_DateLoaded == _DateToCompareWith)
// unreachable code detected :))

Obviously, the Tick-Count is not equal. How do I get on about saving DateTime
values to a Database. Should I store the ticks instead of the dates? Am I
something missing about the DateTime object and its == operator?

In fact, I'm actually not even interested in the Milliseconds part (and
everything beyond that level of precision). I'd just like to compare two dates
based on their Date (DDMMYYYY) and their Time (HHMMSS) values.

Thanks for any help in advance!
 
Hi Matthias,

Most of the compatibility issues get resolved when you use the SqlDateTime
object. Try with this object and see whether it works fine.

HTH,
Rakesh Rajan
 
Matthias,

If all you are worried about is the seconds, then you should make sure
that the milliseconds are not passed in when you create your DateTime
instance. I believe that the DateTime is stored as it is in COM (a double
where the fractional part represents the hours, minutes, seconds,
milliseconds, etc, etc), and because it is a float, is suspect to errors for
numbers with a large number of places.

I would recommend making sure that there are no milliseconds on the
DateTime value when you save it, and that should prove to be just fine.
Your tick counts should come out equal.

Hopet his helps.
 
Back
Top