我想从字符串中提取日期:
"HTTP test [17] 20110515150601.log"
我想知道这个日期是否有效
感谢。
答案 0 :(得分:3)
这是一个小样本应用,展示了如何解析日期。如果您知道格式
,它也可以轻松自定义以解析时间static void Main(string[] args)
{
string source = "HTTP test [17] 20110515150601.log";
Regex regex = new Regex(@"(\d{8})\d*\.log");
var match = regex.Match(source);
if (match.Success)
{
DateTime date;
if (DateTime.TryParseExact(match.Groups[1].Value, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine("Parsed date to {0}", date);
}
else
{
Console.WriteLine("Could not parse date");
}
}
else
{
Console.WriteLine("The input is not a match.");
}
Console.ReadLine();
}