I have a string arranged in a way that would match the format yyyy-dd-MM HH:mm:ss
It might look like this 2010-20-12 13:30:00
I need to insert this into a smalldatetime column in SQL Server. The format of the column is
yyyy-MM-dd HH:mm:ss
I need the string to look like this 2010-12-20 13:30:00 or else SQL Server will get the month and day confused.
Thanks for your thoughts
Don’t send your data to SQL server using a string to start with. Instead, use a parameterized SQL statement, and get the driver to do the work for you after you specify a
DateTime. (See the SqlCommand.Parameters documentation for an example.)This is how you should deal with pretty much all values – especially those entered by users. As well as not having to worry about formatting, this will prevent SQL injection attacks.
So that just leaves the task of parsing your input string as a
DateTime, which is best done withDateTime.ParseExactorDateTime.TryParseExact, depending on whether you want the result of a parsing failure to be an exception or not.