Search code examples
c#linqasp.net-mvc-5

How to truncate time part from date in linq query?


Hi I am trying to write linq query to get some details from Sql table. I have created column and storing date and time both. while returning i want to ommit time part. May I know is this possible?

  List<returnObject> obj = new List<returnObject>();
obj = (from c in objectDB.NCT_Project
  join user in objectDB.NCT_UserRegistration on c.adminUserId equals user.User_Id
  where c.adminUserId == userId
                       select new returnObject
                       {
                           id = c.project_Id,
                           key = c.key,
                           created = c.createdDate //currently returns datetime
                       }).ToList(); 

Any help would be appreciated. Thank you.


Solution

  • Use DbFunctions.TruncateTime method:

    created = DbFunctions.TruncateTime(c.createdDate)
    

    According to the docs:

    When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.