How can I find the closest valid date for one given as an invalid date string?

This issue is related to an accounting package that spills out text reports with rows of data having invalid dates, for example, February 31 st or September 31 st .

Reports are formatted with spaces and fonts at one interval. My goal is to analyze the data and create a more formal report (SSRS).

What interests me is the situation when the date is invalid and cannot be directly converted to a structure DateTime. The date format from the report MMM-dd-yy(for example, Feb-30-10). I would like to convert invalid date strings to the nearest valid one DateTimein the same month before showing them in the official report. I saw how this was done in two ways at one time as a developer, and very badly, so I want to come up with a simple way to do this (if there is no built-in method that I don't know about).

The first bad method I saw (I can't believe what I even show you!):

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

I hope I do not need to explain what I do not like about this method.

Second bad method:

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"

It makes some kind of sad code, and I'm a sad developer.

. ?

, .

+3
2

, , .

:

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

, , . (, , ), / , 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
0

Source: https://habr.com/ru/post/1760408/


All Articles