2010-08-18 102 views
3

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

回答

6

讀取以前的代碼,最後的代碼幾乎是我所建議的。

下面是代碼的變化:

Return New DateTime(year, month, Math.Min(day, DateTime.DaysInMonth(year, month))) 
0

這裏是我發現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