Get date from string

Suppose I have one of the following lines:

"Hello, I'm a String... This is a Stackoverflowquestion!! Here is a Date: 16.03.2013, 02:35 and yeah, plain text blah blah..-."

"This the other string! :) 22.11.2012. Its a Date you see"

"Here we have 2 Dates, 23.12.2012 and 14.07.2011"

What is the best and fastest way to get these dates from string (in DateTime)?

(Only the first date in a row)

Desired Return:

String 1: 16.03.2013 (as a DateTime)
String 2: 22.11.2012 ("           ")
String 3: 23.12.2012 ("           ")

So, I would call the method something like:

DateTime date1 = GetFirstDateFromString(string1);
+5
source share
4 answers

This will extract, parse and print all the dates in the input text:

var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
foreach(Match m in regex.Matches(inputText))
{
    DateTime dt;
    if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
        Console.WriteLine(dt.ToString());
}

Now, if you just need the first date, you can do this:

static DateTime? GetFirstDateFromString(string inputText)
{
    var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
    foreach(Match m in regex.Matches(inputText))
    {
        DateTime dt;
        if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
            return dt;
    }
    return null;
}

Note that the method returns nullable DateTime, so that it can return null when the string does not contain a date.

+14
source

, , , DateTime.ParseExact, :

public DateTime? GetFirstDateFromString(string input)
{
    DateTime d;

    // Exclude strings with no matching substring
    foreach (Match m in Regex.Matches(input, @"[0-9]{2}\.[0-9]{2}\.[0-9]{4}"))
    {
        // Exclude matching substrings which aren't valid DateTimes
        if (DateTime.TryParseExact(match.Value, "dd.MM.yyyy", null, 
            DateTimeStyles.None, out d))
        {
            return d;
        }
    }
    return null;
}
+5

Try the following:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static DateTime? GetFirstDateFromString(string input);
   {
      string pattern = @"\d{2}\.\d{2}\.\d{4}";
      Match m = Regex.Match(input, pattern);
      DateTime result;
      foreach(string value in match.Groups)  
          if (DateTime.TryParseExact(match.Groups[1], "dd.MM.yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)
              return result;
      return null;
   }
}
+1
source

Create a method whose parameters are a regular expression to catch the date format and the string from which you will extract the date. I believe that if you do not have a format to be used, then it will not be possible to extract the date from a series of alphanumeric characters in a string.

0
source

All Articles