【发布时间】:2018-12-05 03:05:03
【问题描述】:
我正在尝试过滤 DataTable 中的 DateTime 并遇到一个奇怪的过滤问题。
1) 数据和过滤 - 工作正常
public DataTable GetDataTable()
{
DataTable employeeCollection = new DataTable();
var dt = DateTime.Now;
employeeCollection.Columns.Add("EmployeeID", typeof(int));
employeeCollection.Columns[0].ColumnName = "Employee ID";
employeeCollection.Columns.Add("EmployeeName", typeof(string));
employeeCollection.Columns["EmployeeName"].ColumnName = "Employee Name";
employeeCollection.Columns.Add("CustomerID", typeof(string));
employeeCollection.Columns["CustomerID"].ColumnName = "Customer ID";
employeeCollection.Columns.Add("Country", typeof(string));
employeeCollection.Columns.Add("Date", typeof(DateTime));
DateTime date1 = new DateTime(2011, 6, 26, 4, 34, 45);
DateTime date2 = new DateTime(2011, 6, 27, 4, 34, 45);
employeeCollection.Rows.Add(1011, "DintinAmam", "Alfki", "Britain", date1);
employeeCollection.Rows.Add(1012, "JohnAmam", "Johanesberg", "China", date2);
string filterString = "Date = #" + date1.ToString() + "#";
employeeCollection.DefaultView.RowFilter = filterString;
return employeeCollection;
}
过滤字符串 - “日期 = #6/26/2011 4:34:45 AM#”
2) 数据和过滤 - 不起作用
public DataTable GetDataTable()
{
DataTable employeeCollection = new DataTable();
var dt = DateTime.Now;
employeeCollection.Columns.Add("EmployeeID", typeof(int));
employeeCollection.Columns[0].ColumnName = "Employee ID";
employeeCollection.Columns.Add("EmployeeName", typeof(string));
employeeCollection.Columns["EmployeeName"].ColumnName = "Employee Name";
employeeCollection.Columns.Add("CustomerID", typeof(string));
employeeCollection.Columns["CustomerID"].ColumnName = "Customer ID";
employeeCollection.Columns.Add("Country", typeof(string));
employeeCollection.Columns.Add("Date", typeof(DateTime));
DateTime date1 = DateTime.Now.AddDays(1);
DateTime date2 = DateTime.Now.AddDays(2);
employeeCollection.Rows.Add(1011, "DintinAmam", "Alfki", "Britain", date1);
employeeCollection.Rows.Add(1012, "JohnAmam", "Johanesberg", "China", date2);
string filterString = "Date = #" + date1.ToString() + "#";
employeeCollection.DefaultView.RowFilter = filterString;
return employeeCollection;
}
过滤字符串 - “日期 = #6/27/2018 5:19:17 PM#”
输出 2:
使用构造函数创建 DateTime 值时,过滤工作正常,而使用 DateTime.Now 过滤时不起作用。
谁能确认一下,为什么使用 DateTime.Now.AddDays() 初始化 Date 值对过滤不起作用?
【问题讨论】:
-
另一种选择可能是做类似
"Date >= #6/27/2018 5:19:17 PM# AND Date < #6/27/2018 5:19:18 PM#的事情。