【问题标题】:Filtering in DataTable is not working for DateTime.Now or DateTime.AddDaysDataTable 中的过滤不适用于 DateTime.Now 或 DateTime.AddDays
【发布时间】: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#”

输出 1:

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#的事情。

标签: c# winforms datetime


【解决方案1】:

日期/时间值的行过滤器处理亚秒组件(毫秒...)。

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

您的过滤器仅在 date1date2 没有亚秒组件时才起作用,这是您的第一个代码 sn-p 中的情况(此 DateTime 构造函数将它们设置为 0)。

一种解决方案是给ToString 一个包含亚秒组件的格式。

【讨论】:

  • DateTime.ToShortDateString 可以方便地截断时间部分。
猜你喜欢
  • 1970-01-01
  • 2017-11-01
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 2021-01-23
  • 2011-10-18
相关资源
最近更新 更多