Get Date from String

前端 未结 5 578
梦谈多话
梦谈多话 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:29

    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;
    }
    

提交回复
热议问题