-3

I have a Unformatted String (Eg: Sundy/03-1 3-1949) I need to convert this to "dd/MM/yyyy".

My plan is to remove text, spaces, special characters and keep numbers only (Eg: Sundy/03-1 3-1949 --> 03131949)

Then convert the numbers to in date format.(Eg: Sundy/03-1 3-1949 --> 03131949 ---> 13/03/1949)

The Code I used

private void button1_Click(object sender, EventArgs e)
    {
       String stringWithDate = textBox1.Text.ToString();


        if (stringWithDate.ToString() != null && !stringWithDate.ToString().Equals(""))
        {
            DateTime dts;
            String str = stringWithDate.ToString();
            str = Regex.Replace(str, @"[^\d]", "");

            Console.WriteLine("String: " + stringWithDate.ToString() + "\n Removed Spaces: " + str);

            if (DateTime.TryParseExact(str, "MMddyyyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dts))
            {
                String a = dts.ToString("MM/dd/yyyy");
                stringWithDate = a;
                Console.WriteLine("String: " + stringWithDate.ToString() + "\n Removed Spaces: " + str + "\n Date formatted: " + a + "\n");
                label1.Text = (a);
            }

        }

      
    }

The Output is not detecting all types. Is there a way to pass everything

enter image description here

h3r
  • 43
  • 1
  • 1
  • 7
  • 1
    _"My plan is to remove text, spaces, special characters and keep numbers only "_ - what's the game plan for `wed%nes6day`? – ProgrammingLlama Sep 19 '20 at 16:38
  • Also, what kind of date is `19321`? – Wiktor Stribiżew Sep 19 '20 at 16:40
  • `ParseExact()` with a ` MMddyyyy` format requires `03011949` rather than `0311949`. Also, what's with all the extra `ToString()` calls on values that are **already** strings. – Joel Coehoorn Sep 19 '20 at 16:48
  • 1
    Also, `19321` is **ambiguous**. There's no way to know whether they mean `March 21, 2019` or `March 19, 2021`. – Joel Coehoorn Sep 19 '20 at 17:02
  • Oh, and `19321` could also be the number of days since the unix epoch, which would be `November 25,2022`. – Joel Coehoorn Sep 19 '20 at 17:18
  • The only issue is that the numbers have to have a fixed format, number of digits and location. Without that, it can't be done. Otherwise, it's trivial. Taking spaces out of 1 2 30 1 96 3 is trivial also. As long as the amount and order of the digits are constant. –  Sep 19 '20 at 17:34

2 Answers2

2

This will get some of the missing values, but one very important thing to understand is there is no computer program anywhere that can understand any date format a human might input. You need to do better on the front end, guiding humans to input reasonable, consistent, and --above all-- unambiguous values.

private void button1_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(textBox1.Text)) return;

    //normalize
    var str = textBox1.Text;
    if (str.Contains(",")) str = str.Split(",")[1];
    str = Regex.Replace(str.Replace("-","/"), @"[^\d/]", "");
    if (str.StartsWith("/")) str = str.Substring(1);
    Console.WriteLine($"Original: {textBox1.Text}\nNormalized: {str}");

    //parse
    string[] formats = {"MM/dd/yyyy", "MM/d/yyyy"};
    DateTime parsed;
    if (DateTime.TryParseExact(str, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out parsed))
    {
        var result = parsed.ToString("MM/dd/yyyy");
        Console.WriteLine($"Original: {textBox1.Text}\nNormalized: {str}\nParsed: {result}");
        label1.Text = result;
    }     
}

I'd further change this to extract some smaller methods:

private string NormalizeDateInput(string input)
{
    if (string.IsNullOrEmpty(input)) "";

    if (input.Contains(",")) input = input.Split(",")[1];
    input = Regex.Replace(input.Replace("-","/"), @"[^\d/]", "");
    if (input.StartsWith("/")) input = input.Substring(1);
    return input;
}

public DateTime ParseMyDate(string input)
{
    DateTime result = default(DateTime);
    input = NormalizeMyDateInput(input);
    if (string.IsNullOrEmpty(input)) return result;

    DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
    return result;
}

private void button1_Click(object sender, EventArgs e)
{
    DateTime dts = ParseMyDate(textBox1.Text);
    if (dts != default(DateTime))
    {
        label1.Text = dts.ToString("MM/dd/yyyy");
    }
}

One advantage here is you can limit your tinkering to just the NormalizeDateInput() method.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0
string str;
            DateTime dts;
            str = Console.ReadLine();
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c >= '0' && c <= '9'))
                {
                    sb.Append(c);
                }
            }
            string str1 = sb.ToString();
            if (DateTime.TryParseExact(str, "MMddyyyy", 
System.Globalization.CultureInfo.CurrentCulture, 
System.Globalization.DateTimeStyles.None, out dts))
            {
                String a = dts.ToString("MM/dd/yyyy");
                Console.WriteLine(a);
            }


 I tried for "Sundy /    03 - 1 3 - 1949" it is giving me output 03/13/1947.Try to merger this logic with your code and let me know if it is working 
user13573775
  • 19
  • 2
  • 7