0

I was wondering how I would convert a string of four to six digits to a date in C#?

111110 would be 11 11 10

111 10 would be 11 1 10

1 1 10 would be 1 1 10

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

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?

//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 < 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++;
        //Check if the month is done
        if ((peek == ' ' || peek == '\0' || count == 2) && 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) && gotDay == false && 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) && 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;
}
2
  • This is what happens when you don't do enough research on available functions and try to do things from scratch... Commented Nov 10, 2011 at 22:12
  • Is it me or did you just rewrite a new question for one that has been closed one hour before? stackoverflow.com/questions/8086209/… Commented Nov 10, 2011 at 23:38

3 Answers 3

3

You discriminator here is the number of spaces. First get that:

string source = "....";    
int spaceCount = source.Count(c => c == ' ');

Then create formatstrings for the expected range 0..2 . You can use the strings from the question except that you have to use M for the months:

var formats = new string[] { "MMddyy", "MMd yy", "M d yy" };

and then you can get your date :

DateTime r = DateTime.ParseExact(source, formats[spaceCount], null);

Add validations as required.

Sign up to request clarification or add additional context in comments.

Comments

3

Try using

DateTime.TryParseExact(dateString, new string[] { "MMddyy", "MMd yy", "M d yy" }, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out result);

if you need to you can

dateString = dateString.Replace('\0', ' ');

before you begin

1 Comment

That's a much more efficient solution. Thanks!
3

You should use one of the many Parse methods defined on DateTime.

These will take the string, an optional format string (describing the format of the datetime string) and an optional culture.

Take a look at Parse, ParseExact, TryParse and TryParseExact, some of which will take a string[] of the formats to try.

Additionally, here available string formats - standard and custom date and time format strings.

6 Comments

Is there a list of acceptable string formats for DateTime.Parse?
@NexAddo - Yes, there is. Answer amended.
The problem is that he has many format strings he needs to use.
@McKay - some the parse methods take a string[] of the different formats to try. Which you seem to know about from your answer.
@Oded The ParseExact methods do, not the Parse methods. (hence my answer that actually does take an array of formats)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.