tes*_*ing 0 c# linq comparison datetime date
我想在不同的日期之间过滤一些文档.首先,我尝试直接比较日期,但不必考虑时间(小时,分钟,秒).因此,只需要日期部分,但以下方法是错误的:
DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue) {
filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year >= fromDate.Value.Year
&& d.LastModifiedAt.Value.Month >= fromDate.Value.Month
&& d.LastModifiedAt.Value.Day >= fromDate.Value.Day);
}
DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue) {
filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year <= toDate.Value.Year
&& d.LastModifiedAt.Value.Month <= toDate.Value.Month
&& d.LastModifiedAt.Value.Day <= toDate.Value.Day);
}
Run Code Online (Sandbox Code Playgroud)
考虑从日期 8/15/2014 12:00:00 AM和到目前为止 9/15/2014 12:00:00 AM.如果文档具有日期8/16/2014 10:06:25 AM,则不会出现在结果中.原因是我直接比较每个组件(年,月,日).因为当天是16和16> 15,所以不符合最后一个条件.
我怎么解决这个问题?我应该把时间设置为午夜前一分钟吗?或者我应该计算差异?
只需使用该DateTime.Date属性:
if (fromDate.HasValue) {
filterResults = filterResults
.Where(d => d.LastModifiedAt.Date >= fromDate.Value.Date);
}
if (toDate.HasValue) {
filterResults = filterResults
.Where(d => d.LastModifiedAt.Date <= toDate.Value.Date);
}
Run Code Online (Sandbox Code Playgroud)
DateTime有一个Date属性,DateTime在午夜返回同一天:
DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue)
filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date >= fromDate.Value.Date);
DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue)
filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date <= toDate.Value.Date);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1407 次 |
| 最近记录: |