Pregunta

My user will typically enter some trip info including a day and month but typically they just enter the day. For example they would enter "TRIP1500/31" where the 31 is implied that its in JULY. The trip date can be at most 7 days in the past or 7 days in the future. So now what Im trying to do is guess what month that day is meant to be. So far I have:

Dim diff As Integer = CInt(tripDay) - Date.Now.Day
Select Case diff
    Case 0
        'same day so its probably current month
End Select

What I'm having trouble with is the other cases where the current day and the trip day overlap month-to-month. If the current day and trip day are in current month then the most difference they can be is +/-7 days but what about the other cases? Any help appreciated.

¿Fue útil?

Solución

Function GetTripDate(day As Integer) As Date

    Dim today As Date = Date.Today

    For i As Integer = -7 To 7
        Dim dt As Date = today.AddDays(i)
        If dt.Day = day Then Return dt
    Next

    Throw New ArgumentOutOfRangeException("Invalid trip day.")

End Function

Otros consejos

This gives you the date(incl. month) of the nearest date with the given day:

Dim maxDiffDays = 7
Dim tripDay = 31
Dim today = Date.Today
Dim tripDate = New Date(today.Year, today.Month, tripDay)
Dim tripDates = {tripDate.AddMonths(-1), tripDate, tripDate.AddMonths(1)}
Array.Sort(Of Date)(tripDates, Function(d1, d2) ((today - d1).Duration).CompareTo((today - d2).Duration))
Dim nearestDate = tripDates.First()
If ((today - nearestDate).Days <= maxDiffDays) Then
    Console.WriteLine("Nearest month for trip date is: " & nearestDate.Month)
End If

It creates a Date from a given day, then it creates the two surrounding dates one month after and previous this date. This array will be sorted from the positive timespan from today(TimeSpan.Duration). So the firs't date in the array is the nearest date with the correct month.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top