使用正则表达式在C#中解析多个日期格式

3

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

04-2014
April, 2014
April,2014

我想出了以下代码,可以让我配置一个包含所有可能格式的字典,其中包括它们的正则表达式和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
}

任何输入都受到赞赏!

旁注:2014-05-07?还是2014-07-05?有时猜测日期时间格式,随机数看起来就非常可靠 :) - Alexei Levenkov
Alexei,谢谢你的警告。我知道这个事实,我们需要处理输入值。 - bigmac
1个回答

7
你不需要正则表达式。你可以使用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);
    }
}

1
这就是我一直在寻找的。感谢EZI帮助我找到了那个方法。 - bigmac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接