Get Date from String
If your dates are always in that format, you could try using a regex to grab the date string and then use DateTime.ParseExact
to get the result you want:
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;
}
This will extract, parse and print all 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 want the first date, you can do that:
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 a nullable DateTime
, so that it can return null when the string contains no date.
Try this:
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;
}
}