How to compare DateTime without time via LINQ?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When comparing DateTime values in C# LINQ queries, the time component (hours, minutes, seconds) is included by default. Two records from the same day but different times will not be considered equal. To compare only the date portion, use the .Date property (which zeros out the time), DateOnly (.NET 6+), or DbFunctions.TruncateTime in Entity Framework. The approach depends on whether the query runs in memory (LINQ to Objects) or is translated to SQL (LINQ to Entities/EF Core).
The Problem
LINQ to Objects: Use .Date Property
For in-memory collections, DateTime.Date returns a new DateTime with the time set to 00:00:00.
Entity Framework Core: .Date in Queries
EF Core can translate .Date to SQL for most database providers.
Entity Framework 6: DbFunctions.TruncateTime
In older Entity Framework 6, .Date is not supported in LINQ queries. Use DbFunctions.TruncateTime instead.
Range-Based Comparison (Most Efficient for SQL)
Instead of stripping the time, use a range that covers the entire day. This is index-friendly because it does not wrap the column in a function.
Using DateOnly (.NET 6+)
Grouping by Date (Ignoring Time)
Common Pitfalls
- Using
.Datein Entity Framework 6 queries: EF6 cannot translateDateTime.Dateto SQL and throwsNotSupportedException. UseDbFunctions.TruncateTime()in EF6 queries. EF Core handles.Datecorrectly. - Function-wrapped columns preventing index use:
WHERE CONVERT(date, CreatedAt) = @datecannot use an index onCreatedAt. For large tables, use range comparison (>= dayStart AND < dayEnd) instead, which allows the database to use indexes. - Time zone mismatches: Comparing
DateTime.Datewhen values are in different time zones gives wrong results. A UTC timestamp of2025-03-15T23:00:00Zis March 16 in UTC+2. Normalize to the same time zone before comparing dates. - Comparing
DateTimewithDateTime?(nullable): If the column is nullable,o.CreatedAt.Value.DatethrowsNullReferenceExceptionwhen the value is null. Filter nulls first:.Where(o => o.CreatedAt.HasValue && o.CreatedAt.Value.Date == target). - Off-by-one in day-end boundary: Using
<= dayEndinstead of< dayEndincludes records at exactly midnight of the next day. Always use exclusive upper bound:CreatedAt < targetDate.AddDays(1).
Summary
- Use
.Dateproperty in LINQ to Objects to strip the time component - Use
DbFunctions.TruncateTime()in Entity Framework 6 queries - Use range comparison (
>= start AND < end) for index-friendly SQL queries - Use
DateOnly(.NET 6+) for columns that should never have a time component - Always consider time zones when comparing dates across different systems

