DataTable中的过滤不适用于DateTime.Now或DateTime.AddDays

时间:2018-06-26 11:43:24

标签: c# winforms datetime

我正在尝试过滤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#”

输出1: enter image description here

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:

enter image description here

使用构造函数创建DateTime值时,过滤工作正常,使用DateTime时,现在过滤不起作用。

任何人都可以确认我,为什么使用DateTime.Now.AddDays()初始化Date值无法过滤?

1 个答案:

答案 0 :(得分:2)

用于日期/时间值的行过滤器处理秒级以下的分量(毫秒...)。

但是日期/时间的默认格式不包括这些内容。

仅当date1date2没有次级组件时,您的过滤器才能工作,在您的第一个代码段中就是这种情况(此DateTime构造函数将它们设置为0)。

一种解决方案是给ToString一种格式,该格式确实包含次秒部分。