Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c# - Linq - Select Date from DateTime

I have a Linq Result from which I need to select only Date from DateTime.
My Query goes like this :

var UserTemplates = (from xx in VDC.SURVEY_TEMPLATE
                     where xx.USER_ID == userid && xx.IS_ACTIVE == 1
                     select new
                     {
                       xx.TEMPLATE_ID,
                       xx.TEMPLATE_NAME,
                       //CREATED_DATE = xx.CREATED_DATE.Value.Date
                       //CREATED_DATE = EntityFunctions.TruncateTime(xx.CREATED_DATE)
                       xx.CREATED_DATE
                     }).ToList();

Is that Possible? Any help would be greatly appreciated.

CREATED_DATE - `datetime` datatype

Actually,I'm Binding it to a Control as a DataSource and the control is displaying both Date and Time.But I want to display only date.

When I'm trying with CREATED_DATE = xx.CREATED_DATE.Value.Date,It is giving an error like :

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If it is for presentation purpose, then you can use DataFormatString property. For Example, if you are binding a datasource to a GridView, you could do as;

<asp:BoundField DataField="CREATED_DATE" ...
     DataFormatString="{0:d}" ../>

Else you can use EntityFunctions.TruncateTime() which returns the input date without the time portion.

EntityFunctions.TruncateTime(xx.CREATED_DATE)

Your query would be like;

var UserTemplates = (from xx in VDC.SURVEY_TEMPLATE
                     where xx.USER_ID == userid && xx.IS_ACTIVE == 1
                     select new
                     {
                       xx.TEMPLATE_ID,
                       xx.TEMPLATE_NAME,
                       EntityFunctions.TruncateTime(xx.CREATED_DATE) //new like
                     }).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...