Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 556
RealSteel Avatar asked Sep 26 '13 07:09

RealSteel


Video Answer


2 Answers

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();
like image 116
Kaf Avatar answered Sep 21 '22 01:09

Kaf


Use this...It worked for me..

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=SqlFunctions.DateName("day", xx.CREATED_DATE).Trim() + "/" +
        SqlFunctions.StringConvert((double)xx.CREATED_DATE.Value.Month).TrimStart() + "/" +
        SqlFunctions.DateName("year", xx.CREATED_DATE)
         }).ToList();

And Output Date will be dd/MM/yyyy format

like image 39
Dharmendra Prajapati Avatar answered Sep 24 '22 01:09

Dharmendra Prajapati