converting a string to a date in C#
<p>I was wondering how I would convert a string of four to six digits to a date in C#?</p>

<p><code>111110 would be 11 11 10</code></p>

<p><code>111 10 would be 11 1 10</code></p>

<p><code>1 1 10 would be 1 1 10</code></p>

<p>The pattern being <code>mmddyy</code> <code>mmd yy</code> <code>m d yy</code>
and the spaces are either <code>' '</code> or <code>'\0'</code> (the input I am given is not very clean)</p>

<p>This what I have so far and it works for all above cases, its just not very pretty:
Is there a more efficient solution to the above cases?</p>

<pre><code>//Converts the given input string into a valid Date
private DateTime convertToDateFromString(string dateString)
{
  int length = dateString.Length;
  int month = 1;
  int day = 1;
  int year = 1;
  bool gotMonth = false;
  bool gotDay = false;
  bool gotYear = false;
  char c = ' ';
  char peek = ' ';
  string buffer = "";
  DateTime bufferDate;
  int count = 0;

  try
  {
    //loop character by character through the string
    for (int i = 0; i &lt; dateString.Length; i++)
    {
      c = dateString[i];
      if ((i + 1) &lt; dateString.Length)
        peek = dateString[i + 1];
      else
        peek = '\0';

      if (c != ' ' &amp;&amp; c != '\0')
      {
        buffer += c;
        count++;
        //Check if the month is done
        if ((peek == ' ' || peek == '\0' || count == 2) &amp;&amp; gotMonth == false)
        {
          count = 0;
          gotMonth = true;
          month = int.Parse(buffer);
          buffer = null;
        }
        //Check if the day is done
        else if ((peek == ' ' || peek == '\0' || count == 2) &amp;&amp; gotDay == false &amp;&amp; gotMonth == true)
        {
          count = 0;
          gotDay = true;
          day = int.Parse(buffer);
          buffer = null;
        }
        //Check if the year is done
        else if ((peek == ' ' || peek == '\0' || count == 2) &amp;&amp; gotYear == false &amp;&amp; gotMonth == true &amp;&amp; gotDay == true)
        {
          count = 0;
          gotYear = true;
          year = int.Parse(buffer);
          buffer = null;

          if (year &gt;= 80 &amp;&amp; year &lt;= 99)
            year += 1900;
          else if (year &gt;= 0 &amp;&amp; year &lt;= 79)
            year += 2000;
        }
      }
    }
    bufferDate = new DateTime(year, month, day);
  }
  catch (System.Exception ex)
  {
    bufferDate = new DateTime(1, 1, 1);
  }
  return bufferDate;
}
</code></pre>
