How to check date format c#

.net, c#, date-format

Solution

One of the overloads of TryParseExact accepts as its second parameter an array of strings. It won't tell you exactly which format was used, however. If you really do need that information, then yes, you're just going to have to run the one-format TryParseExact with each format you want, and see which one works.

And, of course, you'll need to make sure that all the formats you allow are unambiguous as to which parts are day, month, and year, or else you might parse 01/02/03 as any of six possible dates.

Problem

I have a c# block of code here: ``` string inputString = textBox1.Text; DateTime dt; try { if (DateTime.TryParseExact(inputString, "yyyyMMdd", null, DateTimeStyles.None, out dt) == true) { dt = dt.AddMonths(6); textBox2.Text = dt.ToString("yyyyMMdd"); } else if (DateTime.TryParseExact(inputString, "yyyy.MM.dd", null, DateTimeStyles.None, out dt) == true) { dt = dt.AddMonths(6); textBox2.Text = dt.ToString("yyyyMMdd"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } ``` Basically, what it does is, user input a string in textbox1, on button click, C# will check what date format is in the textbox, then add 6 months on the date and output it in the textbox2 to string format yyyyMMdd. As you see as of now, it accepts yyyyMMdd and yyyy.MM.dd and do the same process. But my problem is I still got a lot of date format left: ``` dd-MM-yy yyyy/mm/dd yyyy-mm-dd yy/mm/dd ``` I don't want to use OR in my IF statement. Is there a way like WHATEVER the format is, will be accepted and do the process. Thanks a lot guys!

Original source