117

我有两个日期值,一个已经存储在数据库中,另一个由用户使用 DatePicker 选择。用例是从数据库中搜索特定日期。

先前在数据库中输入的值始终具有 12:00:00 的时间分量,其中从选取器输入的日期具有不同的时间分量。

我只对日期组件感兴趣,并想忽略时间组件。

在 C# 中进行这种比较的方法是什么?

另外,如何在 LINQ 中执行此操作?

更新:在 LINQ to Entities 上,以下工作正常。

e => DateTime.Compare(e.FirstDate.Value, SecondDate) >= 0
4

14 回答 14

136

使用该类EntityFunctions来修剪时间部分。

using System.Data.Objects;    

var bla = (from log in context.Contacts
           where EntityFunctions.TruncateTime(log.ModifiedDate) ==  EntityFunctions.TruncateTime(today.Date)
           select log).FirstOrDefault();

资料来源:http ://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/

更新

从 EF 6.0 及更高版本开始,EntityFunctions 被 DbFunctions取代

于 2012-03-09T23:20:31.663 回答
123

注意:在撰写此答案时,EF 关系尚不清楚(在撰写此答案后已编辑到问题中)。有关 EF 的正确方法,请检查Mandeeps answer


您可以使用该DateTime.Date属性执行仅日期比较。

DateTime a = GetFirstDate();
DateTime b = GetSecondDate();

if (a.Date.Equals(b.Date))
{
    // the dates are equal
}
于 2009-09-25T16:10:09.380 回答
25

我认为这可以帮助你。

我进行了扩展,因为我必须比较充满 EF 数据的存储库中的日期,因此 .Date 不是一个选项,因为它没有在 LinqToEntities 翻译中实现。

这是代码:

        /// <summary>
    /// Check if two dates are same
    /// </summary>
    /// <typeparam name="TElement">Type</typeparam>
    /// <param name="valueSelector">date field</param>
    /// <param name="value">date compared</param>
    /// <returns>bool</returns>
    public Expression<Func<TElement, bool>> IsSameDate<TElement>(Expression<Func<TElement, DateTime>> valueSelector, DateTime value)
    {
        ParameterExpression p = valueSelector.Parameters.Single();

        var antes = Expression.GreaterThanOrEqual(valueSelector.Body, Expression.Constant(value.Date, typeof(DateTime)));

        var despues = Expression.LessThan(valueSelector.Body, Expression.Constant(value.AddDays(1).Date, typeof(DateTime)));

        Expression body = Expression.And(antes, despues);

        return Expression.Lambda<Func<TElement, bool>>(body, p);
    }

那么你可以这样使用它。

 var today = DateTime.Now;
 var todayPosts = from t in turnos.Where(IsSameDate<Turno>(t => t.MyDate, today))
                                      select t);
于 2009-11-18T23:59:18.883 回答
11

如果您使用DateDB 实体的属性,您将获得异常:

"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

你可以使用这样的东西:

  DateTime date = DateTime.Now.Date;

  var result = from client in context.clients
               where client.BirthDate >= date
                     && client.BirthDate < date.AddDays(1)
               select client;
于 2012-07-26T08:48:30.140 回答
9

要在 LINQ to Entities 中执行此操作,您必须使用支持的方法

var year = someDate.Year;
var month = ...
var q = from r in Context.Records
        where Microsoft.VisualBasic.DateAndTime.Year(r.SomeDate) == year 
              && // month and day

丑陋,但它可以工作,并且是在数据库服务器上完成的。

于 2009-09-30T16:46:30.780 回答
8

这是一种不同的方法,但只有在 SecondDate 是您传入的变量时才有用:

DateTime startDate = SecondDate.Date;
DateTime endDate = startDate.AddDays(1).AddTicks(-1);
...
e => e.FirstDate.Value >= startDate && e.FirstDate.Value <= endDate

我认为这应该有效

于 2011-07-01T17:12:05.137 回答
7

你也可以使用这个:

DbFunctions.DiffDays(date1, date2) == 0

于 2015-12-17T16:46:00.487 回答
5

您可以为此使用 DbFunctions.TruncateTime() 方法。

e => DbFunctions.TruncateTime(e.FirstDate.Value) == DbFunctions.TruncateTime(SecondDate);
于 2016-11-11T06:26:31.853 回答
3

我就是这样做的。

DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
                EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));
于 2014-02-17T09:25:38.563 回答
3

总是比较 DateTime 的Date属性,而不是完整的日期时间。

当您进行 LINQ 查询时,请在查询中使用 date.Date,即:

var results = from c in collection
              where c.Date == myDateTime.Date
              select c;
于 2009-09-25T16:10:19.983 回答
2

//Linq 用户/编码员注意事项

这应该为您提供准确的比较,以便在使用来自用户的输入时检查日期是否在范围内 - 例如日期选择器:

((DateTime)ri.RequestX.DateSatisfied).Date >= startdate.Date &&
        ((DateTime)ri.RequestX.DateSatisfied).Date <= enddate.Date

其中 startdate 和 enddate 是来自日期选择器的值。

于 2011-08-04T16:01:21.393 回答
1

您可以使用以下链接来比较 2 个没有时间的日期:

private bool DateGreaterOrEqual(DateTime dt1, DateTime dt2)
        {
            return DateTime.Compare(dt1.Date, dt2.Date) >= 0;
        }

private bool DateLessOrEqual(DateTime dt1, DateTime dt2)
        {
            return DateTime.Compare(dt1.Date, dt2.Date) <= 0;
        }

比较函数返回 3 个不同的值:-1 0 1 表示 dt1>dt2, dt1=dt2, dt1

于 2012-04-18T09:36:03.500 回答
1

没有时间比尝试这样:

TimeSpan ts = new TimeSpan(23, 59, 59);
toDate = toDate.Add(ts);
List<AuditLog> resultLogs = 
    _dbContext.AuditLogs
    .Where(al => al.Log_Date >= fromDate && al.Log_Date <= toDate)
    .ToList();
return resultLogs;
于 2012-02-18T06:55:24.393 回答
0

试试这个......它可以很好地比较两个 DateTimes 类型之间的 Date 属性:

PS。这是一种权宜之计,也是一种非常糟糕的做法,当您知道数据库可以带来数千条记录时,永远不要使用它......

query = query.ToList()
             .Where(x => x.FirstDate.Date == SecondDate.Date)
             .AsQueryable();
于 2012-02-06T16:58:43.900 回答