Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Dateformat in C# for Inserting to sql server

Tags:

c#

I have a textbox with date format dd/MM/yyyy that I want to convert to the format yyyy-MM-dd to insert it into a database.

I tried

Convert.DateTime/DateTime.ParseExact 

but it always give me the system's default date format.

I don't know any other method to convert it in C#...

like image 649
noushad Avatar asked Dec 01 '25 05:12

noushad


1 Answers

You shouldn't be converting it to a string at all to insert it into your database. (I'm surprised at all the other answers which are recommending this approach.)

Instead, you should be using parameterized SQL, and set the value of the parameter to the DateTime value you've got. You should be using parameterized SQL anyway to avoid SQL injection attacks, and to keep your code and data separate. The fact that it avoids unnecessary string conversions (each of which is a potential pain point) is yet another benefit.

This part of your question suggests you've got a fundamental misconception:

I used Convert.DateTime/DateTime.ParseExact it always give me system date format.

Those methods will give you a DateTime. A DateTime doesn't have a format. When you call ToString you just get the default format for the current culture, but that's not part of the value. It's like with numbers - 16 and 0x10 are the same number, and the int doesn't "know" whether it's in decimal or hex; it's a meaningless concept.

All of this goes beyond your immediate problem, towards trying to keep your code base clean in terms of types. You should keep data in its most appropriate form for as much of the time as you possibly can, and make sure you understand exactly what that data means at all points. Conversions to other types (such as strings) for communication should be done only at API/system boundaries, and avoided even there if possible (e.g. using parameterized SQL as in this case).

like image 52
Jon Skeet Avatar answered Dec 02 '25 19:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!