bigmac
bigmac

Reputation: 2553

Parse Multiple Date Formats using RegEx in C#

Using C# 4.5 I have a need to be able to accept dates in multiple string formats and need to be able to parse them them all into valid dates. Examples include:

04-2014
April, 2014
April,2014

I have come up with the following code that allows me to configure a dictionary with all the possible formats with their representative RegEx format and the .NET equivalent for DateTime.ParseExact. This solution works... however, there's a lot of foreach and if blocks and I just want to find out if there is a more elegant/clean/faster solution.

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
}

Any input is appreciated!

Upvotes: 3

Views: 1480

Answers (1)

EZI
EZI

Reputation: 15364

You don't need Regex. You can use 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);
    }
}

Upvotes: 7

Related Questions