从String获取日期

eMi*_*eMi 6 c# string datetime

可以说我有以下字符串之一:

"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"
Run Code Online (Sandbox Code Playgroud)

从字符串(in DateTime)中获取这些日期的最佳和最快方法是什么?

(仅在字符串中出现第一个日期)

理想的回报:

String 1: 16.03.2013 (as a DateTime)
String 2: 22.11.2012 ("           ")
String 3: 23.12.2012 ("           ")
Run Code Online (Sandbox Code Playgroud)

所以我会调用一个方法,如:

DateTime date1 = GetFirstDateFromString(string1);
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 14

这将提取,解析和打印输入文本中的所有日期:

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());
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您只想要第一个日期,您可以这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,该方法返回一个可为空的DateTime,因此当字符串不包含日期时,它可以返回null.


Ant*_*t P 6

如果您的日期始终采用该格式,您可以尝试使用正则表达式获取日期字符串,然后使用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;
}
Run Code Online (Sandbox Code Playgroud)