.net DataTable.Select 日期格式问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1865912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataTable.Select date format problem
提问by Simon
I'm filtering a datatable on a date range using DataTable.Select, my criteria string is:
我正在使用 DataTable.Select 在日期范围内过滤数据表,我的标准字符串是:
"CreatedOn >='03/11/2009 00:00:00' AND CreatedOn <='03/11/2009 23:59:00'"
This filter returns no rows (even though I can see matching rows in the unfiltered datatable). However I notice if I change the criteria to (note the day/month transposition):
此过滤器不返回任何行(即使我可以在未过滤的数据表中看到匹配的行)。但是我注意到如果我将标准更改为(注意日/月换位):
"CreatedOn >='11/03/2009 00:00:00' AND CreatedOn <='11/03/2009 23:59:00'"
The datatable filters as expected. Clearly this seems to be a date localisation issue, is there an easy way to format the date to avoid this issue?
数据表按预期过滤。显然,这似乎是一个日期本地化问题,是否有一种简单的方法来格式化日期以避免此问题?
回答by AdaTheDev
Use a standard ISO format datetime like this (for 3rd Nov):
使用这样的标准 ISO 格式日期时间(对于 11 月 3 日):
"CreatedOn >='2009-11-03 00:00:00' AND CreatedOn <='2009-11-03 23:59:00'"
In fact, if you want all records created on 3rd Nov, you should really do this as you also want records created in that last minute e.g. 23:59:30:
事实上,如果您希望在 11 月 3 日创建所有记录,您应该这样做,因为您还希望在最后一分钟创建记录,例如 23:59:30:
"CreatedOn >='2009-11-03' AND CreatedOn < '2009-11-04'"
There's a quick reference here
有一个快速参考这里
回答by bniwredyc
Try this:
尝试这个:
string selectString = String.Format("CreatedOn >= '{0}' AND CreatedOn <= '{1}'",
startDate.ToString(DateTimeFormatInfo.InvariantInfo),
endDate.ToString(DateTimeFormatInfo.InvariantInfo));
dt.Select(selectString);
回答by Adriaan Stander
See if you can format you date to "dd MMM yyyy" rather than "MM/dd/yyyy".
看看您是否可以将日期格式化为“dd MMM yyyy”而不是“MM/dd/yyyy”。
something like this
像这样的东西
dt.Select(String.Format("col >= '{0}'", new DateTime(2008, 12, 11).ToString("dd MMM yyyy")))

