Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with Linq query and date format
    text
    copied!<p>I have a C# console application written using Visual Studio 2008.</p> <p>My system culture is en-GB. I have a Linq query that looks like this:</p> <pre><code>var myDate = "19-May-2010"; var cus = from x in _dataContext.testTable where x.CreateDate == Convert.ToDateTime(myDate) select x; </code></pre> <p>The resulting SQL query generates and error because it returns the dates as "19/05/2010" which it interprets as an incorrect date. For some reason even though my system culture is set to en-GB it looks like it's trying to intrepret it as a en-US date.</p> <p>Any ideas how I get around this?</p> <p>Edit: Thanks for the comments about magic strings and var abuse, but that's not my problem. My problem is that in the conversion from Linq to SQL the dates are being interpreted as US format dates (19/05/2010 is being interpreted as: month nineteen, day 5 and year 2010) resulting in the following error:</p> <pre><code>System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value </code></pre> <p>The where clause of the resulting SQL query looks like:</p> <pre><code>WHERE ([t0].[CreateDate] = '19/05/2010 00:00:00') </code></pre> <p>Please note that the exact same Linq query works perfectly in LinqPad.</p> <p>I've tried the following where clause:</p> <pre><code>where x.CreateDate == DateTime.Today </code></pre> <p>and still get the error.</p> <p>Additional Information:</p> <p>SQL Server Query Visualizer:</p> <pre><code>SELECT [t0].[field1], [t0].[field2], [t0].[field3] AS [field4], [t0].[field5] FROM [dbo].[table] AS [t0] WHERE ([t0].[CreateDateTime] = '19/05/2010 00:00:00') Original query: SELECT [t0].[field1], [t0].[field2], [t0].[field3] AS [field4], [t0].[field5] FROM [dbo].[table] AS [t0] WHERE ([t0].[CreateDateTime] = @p0) ------------------------------- @p0 [DateTime]: 19/05/2010 00:00:00 </code></pre> <hr> <p>LINQPad:</p> <pre><code>-- Region Parameters DECLARE @p0 DateTime SET @p0 = '2010-05-19 00:00:00.000' -- EndRegion SELECT [t0].[field1], [t0].[field2], [t0].[field3] AS [field4], [t0].[field5] FROM [table] AS [t0] WHERE ([t0].[CreateDateTime] = @p0) </code></pre> <p>In the above I notice that LinqPad presents the date in a different format to VS.</p> <p>Thanks.</p> <p>Alan T</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload