我的用户通常会输入一些旅行信息,包括日期和月份,但通常只是输入当天。例如,他们将进入"TRIP1500/31"
,其中31表示其在7月。旅行日期可以是过去最多7天或将来7天。所以现在我想做的就是猜猜那一天是什么月份。到目前为止,我有:
Dim diff As Integer = CInt(tripDay) - Date.Now.Day
Select Case diff
Case 0
'same day so its probably current month
End Select
我遇到的问题是当天和旅行日每月重叠的其他情况。如果当前的一天和旅行日在当月,那么最大的差异可能是+/- 7天,但其他情况呢?任何帮助表示赞赏。
答案 0 :(得分:2)
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
答案 1 :(得分:1)
这将为您提供给定日期的最近日期的日期(包括月份):
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
它会在某一天创建Date
,然后在此日期之后一个月创建两个周围日期。此数组将从今天的正时间跨度(TimeSpan.Duration
)中排序。所以数组中的第一个日期是最接近正确月份的日期。