在某一天结束时获取DateTime

Nea*_*hal 2 c# datetime

我有以下内容

 DateTime today = DateTime.Today; // or DateTime.UtcNow.Date;
Run Code Online (Sandbox Code Playgroud)

现在,我不能在Linq-EF中做这样的事情因为Date无法转换为SQL:

 context.Records.Where(r => r.CreationDate.Date == today);
Run Code Online (Sandbox Code Playgroud)

所以,我总是这样做:

 DateTime dayEnd = today.AddDays(1).AddMilliseconds(-1);
 context.Records.Where(r => r.CreationDate >= today && r.CreationDate <= dayEnd);
Run Code Online (Sandbox Code Playgroud)

现在,有没有更好的方法来结束时间DateTime而不是增加一天然后花一毫秒?

Mar*_*zek 5

EntityFunctions.TruncateTime改为使用:

context.Records.Where(r => EntityFunctions.TruncateTime(r.CreationDate) == today);
Run Code Online (Sandbox Code Playgroud)

您还可以AddSeconds(-1)通过将条件更改为<:

DateTime tomorrow = today.AddDays(1);
context.Records.Where(r => r.CreationDate >= today && r.CreationDate < tomorrow);
Run Code Online (Sandbox Code Playgroud)