Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I was wondering if there was a more efficient way of taking strings that represent dates with the pattern being mmddyy or mmd yy or m d yy and converting them into a DateTime object?

111110 would be 11 11 10

111 10 would be 11 1 10

1 1 10 would be 1 1 10

The spaces are either ' ' or '\0' (the input I am given is not very clean)

This is what I have so far, which works for all cases.

//Converts a 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
  {
    for (int i = 0; i < dateString.Length; i++)
    {
      c = dateString[i];
      if ((i + 1) < dateString.Length)
        peek = dateString[i + 1];
      else
        peek = '\0';

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

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

  return bufferDate;
}
share|improve this question

2 Answers 2

up vote 5 down vote accepted

Here's a one-liner for you:

    private DateTime convertToDateFromString(string dateString)
    {
        DateTime bufferDate;

        return DateTime.TryParseExact(
            dateString,
            new[] { "MMddyy", "MMd yy", "M d yy" },
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out bufferDate)
            ? bufferDate
            : new DateTime(1, 1, 1);
    }

With more than one line:

    private DateTime convertToDateFromString(string dateString)
    {
        var allowedFormats = new[] { "MMddyy", "MMd yy", "M d yy" };
        DateTime parsedDate;
        var couldParse = DateTime.TryParseExact(
            dateString,
            allowedFormats,
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out parsedDate);

        if (couldParse)
        {
            return parsedDate;
        }

        return new DateTime(1, 1, 1); // or throw an exception
    }
share|improve this answer
    
The idea is good but the implementation is unreadable. You should use some line breaks. –  palacsint Nov 10 '11 at 22:29
    
Yes, have some. –  Jesse C. Slicer Nov 10 '11 at 22:30
    
Thanks :) Some temporary variable are also useful. I hope you wouldn't mind the edit but I didn't want to write it as a new asnwer. –  palacsint Nov 10 '11 at 22:47
2  
Now you're pushing it :) –  Jesse C. Slicer Nov 10 '11 at 22:50

Here is what I found after more research (Stack Overflow)

private DateTime convertToDateFromString(string s)
{
  string[] formats = new string[] { "MMddyy", "MMd yy", "M d yy" };
  string dateString = s.Replace('\0', ' ');
  dateString = dateString.Trim();

  int spaces = dateString.Count(c => c == ' ');
  DateTime date = DateTime.ParseExact(dateString, formats[spaces], null);

  return date;
}

http://stackoverflow.com/questions/8086726/converting-a-string-to-a-date-in-c-sharp/8086902#8086902

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.