比较DataView.RowFilter中的日期?

Pet*_*ter 12 c# dataview datetime date-format rowfilter

我正在摸索一些相当愚蠢而又显然很难的东西.

DataView dvFormula = dsFormula.Tables[0].DefaultView;
dvFormula.RowFilter = "'" + startDate.ToString("yyyyMMdd") + "' < EndDate OR EndDate = '19000101'";
dvFormula.Sort = "FromDate ASC";
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

无法对System.String和System.DateTime执行'<'操作.

请告诉我解决这个问题的最佳方法是什么.

非常感激!

Dan*_*Dan 24

你需要用#包装日期,而不是撇号.

dvFormula.RowFilter = "#" + startDate.ToString("MM/dd/yyyy") + "# < EndDate OR EndDate = #1/1/1900#"; 
Run Code Online (Sandbox Code Playgroud)

  • @Peter,在英国(我们的日期格式有意义 - dd/mm/yyyy)我必须使用EITHER"yyyy/MM/dd"或美国布局.如果我做ToShortDateString那么它有一个翻转.另外,我建议使用"yyyy/MM/dd"格式,因为它不是特定于语言环境的格式 - 除非有人有更好的信息吗? (5认同)
  • 你是对的#.但关键部分是dateformat需要与系统设置使用的相同.那是多么愚蠢......所以现在我正在使用`startDate.ToShortDateString()`.谢谢你! (4认同)

小智 11

这是解决方案.试试这个:

filter = " (Date >= #" +
         Convert.ToDateTime(txtFromDate.Text).ToString("MM/dd/yyyy") +
         "# And Date <= #" +
         Convert.ToDateTime(txtToDate.Text).ToString("MM/dd/yyyy") +
         "# ) ";
Run Code Online (Sandbox Code Playgroud)


Rya*_*ner 5

根据您的数据提供者,您可能需要使用#字符而不是'字符来转义日期。此外,我会将您的日期格式化为以下格式YYYY-MM-DD,以确保它可以被正确识别为日期。