Thursday, October 25, 2007

.NET DateTime Objects Does Not Compare Correctly

Environment: C#

Symptom:


You have parsed a date time string and made a DateTime object, then you wanted to compare that with current time using DateTime.Now, but it does not work.

DateTime t1 = DateTime.Parse("27 October 2007 10:27");

if (t1 > DateTime.Now) { /* do something */ }

Cause:

The parsed DatTime object has the Kind attribute set to UNKNOWN while DateTime.Now is set to LOCAL. Comparison between the two will not work as expected.

Fix:

There may be other ways of doing this, but here is the one that made my code to work.

DateTime t1 = DateTime.Parse("27 October 2007 10:27");
t1 = DateTime.SpecifyKind(t1, DateTimeKind.Local);
if (t1 > DateTime.Now) { /* do something */ }


Time Wasted:

Took me about 2 hours to figure out what is exactly going on and how to fix it.

No comments: