Search code examples
c#globalization

How to convert MM/dd/yyyy to yyyy/MM/dd in C# using globalization


I have a text box in which a user is supposed to enter a date in MM/dd/yyyy format. This date is stored as yyyy/MM/dd in the database.

I want the user to enter the date in MM/dd/yyyy format and later I want to convert it to yyyy/mm/dd so that I can query the database.

How can I convert the user input date MM/dd/yyyy to yyyy/mm/dd?


Solution

  • If you're certain of the input string's format, use DateTime.ParseExact specifying "MM/dd/yyyy", then return the DateTime using .ToString with the appropriate "yyyy/MM/dd" format string.

    There's no need to reference anything in the System.Globalization namespace for this.

    That said, your database should be storing dates with a datetime format, rather than a string, in which case the format doesn't matter as your DBMS should do the conversion for you.