Main objective is to convert a dd/MM/yyyy to yyyy-MM-dd "date" format to fit in SQL
Don't! You should avoid string conversions as far as you possibly can. Keep your data in its natural representation for as much of the time as you can.
You may well need to parse the date from dd/MM/yyyy
to DateTime
to start with (although if you can avoid even this, do so - we don't know where your data comes from), but then you should leave it as a DateTime
. Use parameterized SQL instead, passing the value of the parameter to the database as a DateTime
. Of course, you should also make sure that the fields in your database are using the appropriate type to start with (not varchar
). Ensuring that your schema matches your data is crucial to running a sane system.
The parsing part should be relatively simple. For example:
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
You may want to use a user's culture instead (depending on where the data has come from) and you may want to use DateTime.TryParseExact
instead (if this is user-entered data rather than something from machine-to-machine communication).