此問題源於一個會計軟件包,其中包含具有無效日期的數據行的基於文本的報告,如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的答案了。