Wednesday, November 23, 2011

Linq : Datetime comparison issues..

If you have taken a datetime field in the database and you want to compare it with another date using Linq then the below code will not work fine !!

WRONG :
var result = (from c in context.Clients
where c.RFS_OfficeUse.AptWithIntakeCoordDate < DateTime.Now
select c).ToList();
return result;

RIGHT :
var result = (from c in context.Clients
where c.RFS_OfficeUse.AptWithIntakeCoordDate < DateTime.SpecifyKind( DateTime.Now,DateTimeKind.Utc)
select c).ToList();
While creating the schema of database the Ado.net entity model will convert datetime database fields to UTC format automatically, so you need to first convert your datetime to UTC format.

No comments:

Post a Comment