Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq 2 Sql DateTime format to string yyyy-MM-dd

Basically, i need the equivalent of T-SQL CONVERT(NVARCHAR(10), datevalue, 126)

I've tried:

  1. from t in ctx.table select t.Date.ToString("yyyy-MM-dd") but it throws not supported exception
  2. from t in ctx.table select "" + t.Date.Year + "-" + t.Date.Month + "-" + t.Date.Day but i don't think it's an usable solution, because i might need to be able to change the format.

The only option I see is to use Convert.ToString(t.Date, FormatProvider), but i need a format provider, and I'm not sure it works either

FormatProvider doesn't work, String.Format doesn't work (string.Format("{0:yyyy-MM-dd}", t.Date) throws not supported exception too).

like image 937
Bogdan Maxim Avatar asked Mar 11 '10 19:03

Bogdan Maxim


People also ask

How to change date format in Linq query?

How can I convert date format in linq? Return a DateTime and let the presentation layer handle formatting. And when you format, don't use hh without an AM/PM designator... use HH for 24 hours.

How to Convert DateTime to date in c#?

ToLongDateString() − Converts the value of the current DateTime object to its equivalent long date string representation. Returns a string that contains the long date string representation of the current DateTime object. ToString() − One more way to get the date from DateTime is using ToString() extension method.

How to Convert DateTime to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.


1 Answers

Assuming that t.Date is nullable (DateTime?) this could be the problem, try using:

from t in ctx.table select (t.HasValue ? t.Date.Value.ToString("yyyy-MM-dd") : string.Empty );

Edit: Second try

The problem is the translation to SQL; it tries to translate the .ToString() to an SQL representation, and fails. So if you should do the following it should work:

(from t in ctx.table select t.Date).ToList().Select(d => d.ToString("yyyy-MM-dd"))

Or

(from t in ctx.table select t.Date).AsEnumerable().Select(d => d.ToString("yyyy-MM-dd"))

AsEnumerable() transforms the previously used IQueryable into an IEnumerable, thus stopping the generation of the SQL (in case of Linq to SQL) or any other transfromation by the provider implementing the specific IQueryable (e.g. Linq to SQL Provider).

Note, before calling AsEnumerable() you should have completed any actions that you want to be converted to SQL and executed on the database directly.

like image 66
8 revs, 3 users 83% Avatar answered Sep 20 '22 06:09

8 revs, 3 users 83%