使用C# 4.5,我需要能够接受多种日期字符串格式,并将它们解析为有效的日期。例如:
04-2014
April, 2014
April,2014
我想出了以下代码,可以让我配置一个包含所有可能格式的字典,其中包括它们的正则表达式和
DateTime.ParseExact
的.NET等效格式。这个解决方案虽然有效,但有很多foreach
和if
块,我想知道是否有更优雅/简洁/快速的解决方案。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
}
任何输入都受到赞赏!