Format date as "MM/dd/yyyy" from a unstructured string in c# regex and

211 Views Asked by At

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

2

There are 2 best solutions below

0
Joel Coehoorn On

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.

0
user13573775 On
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