Search code examples
c#dateparsingstring-parsing

Extracting a Date value from a string


Forum.

My code reads from an excel file and gets the following string in a variable 'textContainingDate':

"Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions"

What I would like to do is extract the date value from the string. Although there are two dates to be read as a date range, the two dates will always be the same. My thought is, regardless of the scenario, I will be satisfied with the first date I come across.

var dateTime = DateTime.ParseExact(textContainingDate, "MM/dd/yyyy", CultureInfo.CurrentCulture);

I tried using the above statement, which I pieced together from other stackoverflow questions and Googled articles. From what I have read, I believe it fails because it is expecting only a date string.

Any advising on a solution and/or direction towards what text to read to find a solution is appreciated.


Solution

  • You can use Regex.Match to get the first date string you meet. This method returns the first substring that matches a regular expression pattern in an input string.

    string stringWithDate = "Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions";
    Match match = Regex.Match(stringWithDate, @"\d{2}\/\d{2}\/\d{4}");
    string date = match.Value;
    if (!string.IsNullOrEmpty(date)) {
        var dateTime = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.CurrentCulture);
        Console.WriteLine(dateTime.ToString());
    }
    

    What the regular expression \d{2}\/\d{2}\/\d{4} does:
    enter image description here