在C#中使用RegEx解析多个日期格式

时间:2014-07-05 18:26:37

标签: c# regex datetime

使用C#4.5我需要能够接受多种字符串格式的日期,并且需要能够将它们全部解析为有效日期。例子包括:

04-2014
April, 2014
April,2014

我已经提出了以下代码,允许我使用其代表性的RegEx格式和DateTime.ParseExact的.NET等效项来配置具有所有可能格式的字典。这个解决方案有效...但是,有很多foreachif块,我只是想知道是否有更优雅/更干净/更快的解决方案。

DateTime actualDate;
var dateFormats = new Dictionary<string, string> { { @"\d{2}-\d{4}", "MM-yyyy" }, { @"(\w)+,\s\d{4}", "MMMM, yyyy" }, { @"(\w)+,\d{4}", "MMMM,yyyy" } };
var dateValues = new[] { "04-2014", "April, 2014", "April,2014", "Invalid Date" };
var successfulDateParse = false;
foreach (var dateValue in dateValues)
{
    foreach (var dateFormat in dateFormats)
    {
        var regex = new Regex(dateFormat.Key);
        var match = regex.Match(dateValue);
        if (match.Success)
        {
            actualDate = DateTime.ParseExact(match.Value, dateFormat.Value, CultureInfo.InvariantCulture);
            successfulDateParse = true;
            break;
        }
    }
    if (!successfulDateParse)
    {
        // Handle where the dateValue can't be parsed
    }
    // Do something with actualDate
}

感谢任何输入!

1 个答案:

答案 0 :(得分:6)

您不需要正则表达式。您可以使用DateTime.TryParseExact

var dateValues = new[] { "04-2014", "April, 2014", "April,2014", "Invalid Date" };
var formats = new[] { "MM-yyyy","MMMM, yyyy","MMMM,yyyy" };

foreach (var s in dateValues)
{
    DateTime dt;
    if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt) == false)
    {
        Console.WriteLine("Can not parse {0}", s);
    }
}
相关问题