在c#中使用RegEx解析多种日期格式

本文关键字:日期 格式 RegEx | 更新日期: 2023-09-27 18:11:39

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

04-2014
April, 2014
April,2014

我已经想出了下面的代码,允许我配置一个字典与所有可能的格式与他们的代表性RegEx格式和等价的。net DateTime.ParseExact。这个解决方案有效……然而,有很多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
}

任何输入都是赞赏的!

在c#中使用RegEx解析多种日期格式

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