DataTable filter on DateTime coloum

I was surprise to know that 'DateTime.Parse' does not parse fractions of a second and this was messing up our Dataview filter.Here is nice tips from furum.

The Select expression you are using uses DateTime.Parse internally.

DateTime.Parse does not parse fractions of a second, even if you were to include them in your expression. 

I can't see DateTime.Parse ever being changed for backwards compatibility reasons.  You basically have two solutions.

1. Truncate the DateTime to an exact second before inserting in your DataTable, e.g.:

locTimeVariable = TruncateToSecond(System.DateTime.Now.AddDays(i));


There are a number of ways you could implement the "TruncateToSecond" helper method.  Here are two - you might like to test to see which is fastest:

static DateTime TruncateToSecond(DateTime dateTime)
    return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind);


static DateTime TruncateToSecond(DateTime dateTime)
return new DateTime((dateTime.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond, dateTime.Kind );


2. Alternatively you could specify a range of times from N to N + 1 second, for example:

"MyColumn>=#" + locTimeVariable.ToString(DateTimeFormatInfo.InvariantInfo) +
"# AND MyColumn<" + locTimeVariable.AddSeconds(1).ToString(DateTimeFormatInfo.InvariantInfo) + "#";


Suresh Behera


No Comments