简体   繁体   中英

How do I convert a DateTime SELECT in Entity Framework 5 to only SELECT the date portion?

This is not working:

select new Schedules
{
    airDate = EntityFunctions.TruncateTime(schedules.DateSched),
};

schedules.DateSched is type "SQL DateTime".

The above function is returning the date AND time portion of it.

How do I go about assign only the DATE part of schedules.DateSched to my "airDate" variable?

This is what Entity Framework produces:

convert (datetime2, convert(varchar(255), <field>, 102) ,  102) AS [C4] 

And if you select that, you get:

2013-06-24 00:00:00.0000000

I want to get:

06/24/2013

Whatever you get out of SQL is irrelevant to your question: C# only has a DateTime type. There's no Date (only) type in C# to convert to. As such, 2013-06-24 00:00:00.00000 is the closest you'll get to having a Date without a time.

Have you tried formatting the date?

   airDate = EntityFunctions.TruncateTime(schedules.DateSched).ToString("d", 
                      CultureInfo.CreateSpecificCulture("en-US"))),

The DateTime type always has a time component. All EntityFunctions.TruncateTime does is strip off any time value, effectively changing the time component to midnight.

If you only want to display the date component, than use an appropriate format code to display just the date:

string myDate = dateTime.ToString("MM/dd/yyyy");

不幸的是,没有答案对我有帮助,所以我所做的就是在实际的gridView中做到了:

<asp:BoundField HeaderText="Air Date" DataField="AirDate" SortExpression="AirDate" DataFormatString="{0:d}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM