I have a Linq to Entity query that compares dates. I’m querying a SQL server 2008 database whose language is US English. My application handles dates in dd/MM/yyyy format.
itemList = from i in _context.Items
select i;
DateTime utcStartDate = DateTime.SpecifyKind(StartDate, DateTimeKind.Utc);
DateTime utcEndDate = DateTime.SpecifyKind(EndDate, DateTimeKind.Utc);
var items= from i in itemList
where c.ModifiedDate.Date >= utcStartDate.Date &&
c.ModifiedDate.Date <= utcEndDate.Date
select i;
Here StartDate and EndDate are DateTime objects, which are read from textboxes (only dates are entered) and converted to DateTime. Typical values are: {8/3/2012 12:00:00 AM} for 08 March 2012.
This is how the value is specified when the column is updated in the database:
item.ModifiedDate = DateTime.UtcNow.Date;
I cannot change the language settings at the Server. Is there any way to read the data from the SQL server and convert it to the “dd/MM/yyyy” format before comparing the dates?
Alternatively, what fornat should I convert the Datetime variables to so that the comparison works? What is the correct and efficient way to do this?
The format only applies when treating the data as strings. The code shown doesn’t do that! It compares them as dates, transferring the parameters in their binary representation. Thus, there is no ambiguity, and no formatting involved at any point.
Basically, this isn’t a problem. What you are asking is actually pretty similar to saying “how does SQL server order integers as “1,2,…,9,10,11” and not “1,10,11,2,…9” – to which the answer is “because it isn’t treating them as strings”.
To be specific, datetime in sql server is actually treated as a decimal number, with the integer part being the day and the decimal part being the time; any “dd/MM/yyyy” or “yyyy/MM/dd” etc exists only for us poor fleshy readers. The server is not confused by such things.