Get Date from String

前端 未结 5 626
梦谈多话
梦谈多话 2020-12-16 05:11

Lets say I have one of following strings:

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


        
5条回答
  •  渐次进展
    2020-12-16 05:21

    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.

提交回复
热议问题