【问题标题】:Use LINQ to compare the date part of DateTime使用 LINQ 比较 DateTime 的日期部分
【发布时间】:2015-01-16 09:29:50
【问题描述】:

我想过滤不同日期之间的一些文档。首先,我尝试直接比较日期,但不必考虑时间(小时、分钟、秒)。因此只需要日期部分,但下面的做法是错误的:

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);
}

考虑开始日期 8/15/2014 12:00:00 AM截止日期 9/15/2014 12:00:00 AM。如果文档的日期为 8/16/2014 10:06:25 AM,则不会出现在结果中。原因是我直接比较每个组件(年、月、日)。因为当天是 16 和 16 > 15,所以最后一个条件不满足。

我该如何解决这个问题?我应该将时间设置为午夜前一分钟吗?还是我应该计算差异?

【问题讨论】:

    标签: c# linq date datetime comparison


    【解决方案1】:

    只需使用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);
    }
    

    【讨论】:

    • SQL Server 不支持
    【解决方案2】:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 2015-03-12
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多