I have a Textbox in which the user is supposed to enter a date in the format dd/mm/yyyy, this date is stored as yyyy/mm/dd in the database.
So I want the user to enter the date in dd/mm/yyyy format and later I want to convert to yyyy/mm/dd so that I can query database.
How can I convert the user input date dd/mm/yyyy to yyyy/mm/dd?
Quick and maybe dirty:
This, of course, assumes that the content of the Textbox will always be in the assumed format, so their should be checks in before to ensure that. There’s also the much safer way which does not need additional checks:
This will try to parse the content of the Textbox and return it to your via the
out result, if successful, it will return true. Otherwise you can rest assured that the input was either not in the assumed format, or not a valid Date.Please also be aware that
ParseExactwill throw anArgumentNullExceptionor anArgumentExceptionif the conversion fails.The obvious answer to this is: use a DateTimePicker and a parameterized query before wrestling with a string conversion. It will save you a lot of headache in the long run.