DataTable RowFilter on Time component of DateTime column

758 views Asked by At

I have DataColumn named Created of type DateTime in a DataTable and have created a RowFilter expression to return only Rows created after, say, 10 pm on any day:

"SUBSTRING(Convert(Created, 'System.String'),11,8) >= '" + cStartTime + "'"

This should convert the DateTime to a System.String, extract the time element as an 8 character sub-string and compare that with a known string value (cStartTime), e.g. "22:00:00". It should return one row, but returns none.

1

There are 1 answers

1
Tim Schmelter On BEST ANSWER

Don't use this approach, it's very error-prone and not readable to convert a DateTime to String and use sub-string, even if it worked now it could break in future(f.e. if the system is using a different culture). Instead i suggest to use Linq-To-DataTable:

var filtered = from row in dataTable.AsEnumerable()
               let created = row.Field<DateTime>("Created")
               where created.Hour >= 22
               select row;

If you want a DataRow[] use filtered.ToArray(). If you want a new DataTable use filtered.CopyToDataTable().