我如何找到最接近的有效日期作为无效日期字符串给出的日期?
问题描述:
此问题源于一个会计软件包,其中包含具有无效日期的数据行的基于文本的报告,如2月31日st或9月31日st。我如何找到最接近的有效日期作为无效日期字符串给出的日期?
报告使用空格和单间隔字体进行格式化。我的目标是解析所需的数据并生成更正式的报告(SSRS)。
我有兴趣修复的是日期无效且无法直接转换为DateTime
结构的情况。报告中的日期格式为MMM-dd-yy
(例如Feb-30-10
)。 我想将无效日期字符串转换为最近的有效DateTime
,并在的同一个月内显示在正式报告中。在我作为一名开发人员的时候,我已经看到了这种做法有两种方式,都很差,所以我想提出一个简单的方法(如果没有我不知道的内置方式) 。
第一个坏方法,我已经看到了(我真不敢相信我竟然流露出你!):
Dim month As Integer = <Parse out the month from the bad date string>
Dim day As Integer = <Parse out the day from the bad date string>
Dim year As Integer = <Parse out the year from the bad date string>
Dim validDate As DateTime
While True
Try
validDate = New DateTime(year, month, day)
Exit While
Catch ex As ArgumentOutOfRangeException
day -= 1
End Try
End While
我希望我不用解释什么,我不喜欢该方法。
第二个坏方法:
Dim badDateString As String = <Current date string from text report>
Dim validDate As DateTime
If DateTime.TryParseExact(badDateString, "MMM-dd-yy", Nothing, Globalization.DateTimeStyles.None, validDate) Then
Return validDate
End If
badDateString = badDateString.Replace("31", "30")
' ... try the parse again, if still not valid, replace "30" with "29"
' ... try the parse again, if still not valid, replace "29" with "28"
这使一些伤感代码和忧伤的开发商。
我一直在想办法做一个更有效的方法。有任何想法吗?
编辑:
我找到了解决方案,并已经发布了,但我喜欢Guffa的答案了。
答
读取以前的代码,最后的代码几乎是我所建议的。
下面是代码的变化:
Return New DateTime(year, month, Math.Min(day, DateTime.DaysInMonth(year, month)))
答
这里是我发现Guffa回答之前解决方案。它采用日期(月,日,年)的部分,使用该特定月份/年份组合中的天数来验证即将到来的日期部分,并在构建新的DateTime
之前根据需要进行调整。
Dim validDate As DateTime
Dim dayMax As Integer = DateTime.DaysInMonth(year, month)
Dim newDay = day
If day > dayMax OrElse day < 1 Then
newDay = dayMax
End If
validDate = new DateTime(year, month, newDay)
Return validDate