I’m having an issue where a C# DateTime string is failing to convert to a SQL DateTime because it is mysteriously being formatted as a UK date (dd/MM/yyyy). Here is the series of events:
- An object is created on a remote server in the US and serialized to xml.
- The xml is deserialized on a local computer in CA back to an object. The serialized date looks like this: 2011-07-13T09:56:57.0542425
- The application attempts to save the object to the database calling the previously mentioned stored procedure. It (needlessly) converts the date to a string before passing it as a parameter to the sproc using Convert.ToString(DateTime).
- The sproc fails with the SqlException “Error converting data type nvarchar to datetime” because the string it received for its DateTime typed parameter was in the dd/MM/yyyy format (and the database language is English US).
Now, the code shouldn’t be converting the datetime to a string only to be converted back to a datetime in SQL, but this problem just started happening (on more than one computer) after everything was fine for over a year. So I thought the culture of the DB or the OS must have just recently changed causing them to use different date formats. To my surprise, after changing the OS (Windows 7) from English(Canada) to English(US) and restarting, the problem still occurs. To make it even more confusing, the error doesn’t happen when when the same type of object is created locally instead of being deserialized, regardless of the regional settings. The only difference is the serialization version happens in a Windows service and the locally created object version happens in a Windows app. They both use their own copy of the assembly that calls Convert.ToString(DateTime) but they are using the same version of that assembly. I am utterly confused.
P.S. .NET 2.0 & SQL Server 2005
Is it possible that the service is running under an account which has the wrong regional settings?
If so, then perhaps these instructions from Microsoft might apply.