Q:

Convert a string to date format

I want a string value to convert date (yyyy-MM-dd) format.
Below is the code which I tried but it is giving me an exception.
string date = "20141021";
DateTime myDate = DateTime.ParseExact(date ,"yyyy-MM-dd",
                                      CultureInfo.InvariantCulture);

As you can see DateTime expects my string to follow a "2014-10-21" pattern. But I can't modify my string. Is it possible to convert string date: "20141021" to a yyyy-MM-dd format?

A:

What about changing the date format to the actual format your string is? ParseExact demands an exact representation of the format you enter.
So the solution is to change yyyy-MM-dd to yyyyMMdd.
string date = "20141021";
DateTime myDate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

