How to truncate time part from date in linq query?

那年仲夏 提交于 2019-12-23 20:29:26

问题


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.


回答1:


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.




回答2:


All you need to do is call 'Date' property on createdDate.

select new returnObject
                       {
                           id = c.project_Id,
                           key = c.key,
                           created = c.createdDate.Date
                       }).ToList(); 



回答3:


you can try this one.

 created = c.createdDate.ToString("HH:mm")
 created = c.createdDate.ToString("H:mm") 
 created = c.createdDate.ToString("hh:mm tt") 
 created = c.createdDate.ToString("h:mm tt")

also see this question : How to get only time from date-time C#



来源:https://stackoverflow.com/questions/43912381/how-to-truncate-time-part-from-date-in-linq-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!