Convert 20121004 (yyyyMMdd) to a valid date time?
<p>I have a string in the following format <code>yyyyMMdd</code> and I am trying to get it to look like this:</p>

<p><code>yyyy-MM-dd</code></p>

<p>When I try:</p>

<pre><code>string date = "20121004";

Convert.ToDateTime(date).ToString("yyyy-MM-dd");
</code></pre>

<p>I get the error:</p>

<p><code>FormatException: String was not recognized as a valid DateTime.</code></p>

<p>Would the following work or would I run into a problem:</p>

<pre><code>private string GetValidDate(string date,string format)
{
    DateTime result;
    if(DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    {
        return date;
    }
    else if(DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    { 
        return DateTime.ParseExact(date, "yyyyMMdd",
                CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
     }
     else
     {
        return "Invalid Date Format";
     }
}
</code></pre>
