I’ve built a .NET 8 Web API that will eventually replace an existing Core 3.1 project. The API serves various clients and is integrated with SQL Server.
When starting to test the API calls I’ve suddenly starting getting lots of DateTime formatting errors like this:
System.Data.SqlClient.SqlException (0x80131904): The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
After adding some code to write queries to a log file, I can see that DateTime values are being formatted differently – it is now mysteriously adding a full stop or dot after the abbreviated month name.
Example query that causes the error:
SELECT COUNT(*) AS myCount FROM member WHERE CreateDT >= '1 Jun. 2024 00:01'
The date part above is created by the following code:
DateTime.Today.ToString("d MMM yyyy");
The strange thing is it’s not happening when debugging on my test PC. The errors only happen on the server. But both my PC and the server have the same Region and Regional format.
After searching online, this seems to be due to the rules of the “current” culture format. However, I’ve not explicitly set a culture format.
Is there some code I need to add to Program.cs when configuring the WebApplication and Services? How do I fix this properly? I certainly don’t want to just manually change all my .ToString() calls to remove the dot!
1