如何检查字符串是否包含特定格式的日期?

时间:2015-09-02 13:57:53

标签: c# datetime c#-4.0

我想检查字符串是否包含此格式的日期 "Wed, Sep 2, 2015 at 6:40 AM"

我怎样才能在C#中做到这一点?

1 个答案:

答案 0 :(得分:0)

以下是与您的日期格式匹配的格式字符串

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