将错误的日期字符串转换为最接近的有效字符串



例如,我有2017年9月31日(不存在的日期),该字符串的DateTime.ParseExact("31.09.2017", "dd.MM.yyyy", null);返回System.FormatException异常。有没有办法将2017年9月31日改为2017年9日30日,并对所有这些错误的日期进行同样的处理?例如"round"工作:移动到上个月的最后一天或下个月的第一天。

您可以使用以下技术:

DateTime temp;
if (!DateTime.TryParse("31.09.2017", out temp))
temp = GetValidDate("31.09.2017");
DateTime GetValidDate(string _date)
{
int day, year, month;
day = int.Parse(_date.Substring(0, 2));
month = int.Parse(_date.Substring(3, 2));
year = int.Parse(_date.Substring(6, 4));
return new DateTime(year, month, Math.Min(day, DateTime.DaysInMonth(year, month)));
}

结果可能不可预测,但您可以拆分部分,转换为int,然后确保每个部分都在正确的范围内,然后创建一个新的字符串进行解析。我怀疑您只需要对前两个部分(dd和MM)执行此操作,如果超出范围,则只需设置为最接近的边界值。

您可以编写一个自定义格式提供程序并将其与DateTime.ParseExact一起使用,但它可能无法跨区域工作,并且根据您的实现方式,仍可能引发类似The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.的异常。

DateTime.ParseExact Method (String, String, IFormatProvider)

一个例子。

最新更新