如何检查字符串是否包含特定格式的日期?
How to check if string contains date in specific format?
我想检查字符串是否包含这种格式的日期
"Wed, Sep 2, 2015 at 6:40 AM"
.
如何在 C# 中执行此操作?
这是与您的日期格式匹配的格式字符串
"ddd, MMM d, yyyy 'at' h:mm tt"
用法的一个例子
DateTime date;
Boolean isValidDate = DateTime.TryParseExact("Wed, Sep 2, 2015 at 6:40 AM", "ddd, MMM d, yyyy 'at' h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
这是一个代码片段,用于从较大的文本中提取日期字符串,然后将其解析为 DateTime
// example string
String input = "This page was last updated on Wed, Sep 2, 2015 at 6:40 PM";
Regex regex = new Regex(@"[a-z]{3},\s[a-z]{3}\s[0-9],\s[0-9]{4}\sat\s[0-1]?[0-9]:[0-5][0-9]\s(AM|PM)", RegexOptions.IgnoreCase);
Match match = regex.Match(input);
if (match.Success)
{
Group g = match.Groups[0];
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
Console.WriteLine(c.Value);
DateTime date;
Boolean isValidDate = DateTime.TryParseExact(c.Value, "ddd, MMM d, yyyy 'at' h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
if(isValidDate)
{
Console.WriteLine(date);
}
}
}
我想检查字符串是否包含这种格式的日期
"Wed, Sep 2, 2015 at 6:40 AM"
.
如何在 C# 中执行此操作?
这是与您的日期格式匹配的格式字符串
"ddd, MMM d, yyyy 'at' h:mm tt"
用法的一个例子
DateTime date;
Boolean isValidDate = DateTime.TryParseExact("Wed, Sep 2, 2015 at 6:40 AM", "ddd, MMM d, yyyy 'at' h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
这是一个代码片段,用于从较大的文本中提取日期字符串,然后将其解析为 DateTime
// example string
String input = "This page was last updated on Wed, Sep 2, 2015 at 6:40 PM";
Regex regex = new Regex(@"[a-z]{3},\s[a-z]{3}\s[0-9],\s[0-9]{4}\sat\s[0-1]?[0-9]:[0-5][0-9]\s(AM|PM)", RegexOptions.IgnoreCase);
Match match = regex.Match(input);
if (match.Success)
{
Group g = match.Groups[0];
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
Console.WriteLine(c.Value);
DateTime date;
Boolean isValidDate = DateTime.TryParseExact(c.Value, "ddd, MMM d, yyyy 'at' h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
if(isValidDate)
{
Console.WriteLine(date);
}
}
}