get date from datetime in linq and show gridview [duplicate]

前提是你 提交于 2019-12-13 11:01:45

问题


I need to get date from datetime in linq like this:

var items = db.Students.ToList().Select(u => new { bi = u.Birthday.Date });

but items in grid are displayed as follows:

I've seen other questions:

Question1: Linq - Select Date from DateTime

but when I edit code Similarly,

                var items = (from xx in db.Students                                     
                                 select new
                                 {
                                    EntityFunctions.TruncateTime(xx.Birthday)
                                 }).ToList();

I got a error in code!!

Question2: How to get only Date from datetime column using linq

but accepted answer to this question convert date to string!

Question3: Linq to Entity get a Date from DateTime

Answers similar to question1.

aspx for show grid:

<asp:GridView ID="GridView1" runat="server">            
</asp:GridView>

Does anyone have an idea to solve this problem?

Thanks.


回答1:


As you have been told before in your other questions; when you display your grid at some point DateTime.ToString() is called, this results in a default behavior of displaying date and time. The DateTime.Date property simply returns the date part of the DateTime as a DateTime; in other words it returns the same thing but with the time set to exactly 12:00 AM.

To get the only the date as a string, you want to call DateTime.ToShortDateString, see here: https://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring(v=vs.110).aspx

In short this has nothing to do with Linq, the problem occurs when you try to display your DateTime object within your grid and as such needs to be solved by adjusting the formatting of the grid cells.



来源:https://stackoverflow.com/questions/38241422/get-date-from-datetime-in-linq-and-show-gridview

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