Extract Date from a C#String

Asked

Viewed 576 times

3

I need to extract two dates from a string that comes in the following format:

string teste = "Aprovados por autorizantes da aplicação -> 02/03/2018 à > 02/03/2019";

This is the start date and the end date. Fixed I can do this, however this string can come with blank dates, or just the start date or just the end date, so:

string teste = "Aprovados por autorizantes da aplicação -> à > ";
string teste = "Aprovados por autorizantes da aplicação -> à > 02/03/2019";
string teste = "Aprovados por autorizantes da aplicação -> 02/03/2018 à > ";

I would like to know how to take these dates dynamically.

2 answers

5

You should analyze the dates within this string to ensure they are valid dates, so avoid future problems.

With a regular expression and using the method Tryparseexact it is possible to extract the date more safely, however, I did not run all the tests so I suggest you test the function below with several entries to check for unwanted results.

Image of the regex:

ilustração da regex

Function code:

List<string> ExtrairDatas(string str)
{
    var regex = new Regex(@"(?:(?:(?:(?:0?[13578])|(1[02]))/31/(19|20)?\d\d)|(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)|(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))|(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d))"); 

    var datas = new List<string>();

    foreach(Match m in regex.Matches(str))
    {                   
        DateTime dt;

        if (DateTime.TryParseExact(m.Value,"dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) datas.Add(dt.ToString("dd/MM/yyyy"));
    }

    return datas;
}

Complete code:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using static System.Console;

public class Program
{
    public static void Main()
    {
        string teste = "Aprovados por autorizantes da aplicação -> 02/03/2018";     

        ExtrairDatas(teste).ForEach(d => WriteLine(d));
    }

    static List<string> ExtrairDatas(string str)
    {
        var regex = new Regex(@"(?:(?:(?:(?:0?[13578])|(1[02]))/31/(19|20)?\d\d)|(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)|(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))|(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d))"); 

        var datas = new List<string>();

        foreach(Match m in regex.Matches(str))
        {                   
            DateTime dt;

            if (DateTime.TryParseExact(m.Value,"dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) datas.Add(dt.ToString("dd/MM/yyyy"));
        }

        return datas;
    }
}

See working on .NET Fiddle.

Sources:
Regex to match Date
Get Date from String

  • Very good, but the application already does this validation, but thank you very much !!!

0


Try the code below:

string teste = "Aprovados por autorizantes da aplicação -> 02/03/2018 à > 02/03/2019";
string[] testeSplit = teste.Split('>');

string dataIni, dataFim;

dataIni = testeSplit[1].Replace('à', ' ').Trim();
dataFim = testeSplit[2].Trim();
  • Could add a description of the solution?

  • I add? What would it be?? You? No problem :P

  • 3

    The solution is practical, but if the script is saved as ASCII and the input value in string teste for Unicode, the .Replace('à', ' ') may fail, since á in latin1 is different from à in utf8, for example.

  • 1

    Correcting my last sentence: ... may fail, since à in latin1 is different from à in utf8.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.