从String获取日期

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

"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" 

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

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

理想的回报:

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

所以我会称之为方法:

 DateTime date1 = GetFirstDateFromString(string1); 

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

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

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

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

请注意,该方法返回可为空的DateTime ,以便在字符串不包含日期时返回null。

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

试试这个:

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

创建一个方法,其参数是正则表达式,以捕获日期格式和将从中提取日期的字符串。 我相信如果你没有使用的格式,那么就无法从字符串中的一系列字母数字字符中提取日期。