I am currently using the function below to return the nearest date from a list of dates to a date(today). My problem is, the function returns the closest date regardless of it being the past or the future of todays date. How can I change this code so there is an option to return the nearest date AFTER today and the nearest date BEFORE today? It’s confusing the hell out of me.
Thanks a lot for your input.
Function GetNearestDate(ByVal source As IEnumerable(Of DateTime), ByVal target As DateTime) As DateTime
Dim result As DateTime = Nothing
Dim lowestDifference = TimeSpan.MaxValue
For Each _date As DateTime In source
If _date >= target Then
Continue For
End If
Dim difference = target - _date
If difference < lowestDifference Then
lowestDifference = difference
result = _date
End If
Next
Return result
End Function
Seems like this is what you are looking for. you simply need to be able to pass something in to the function so it knows what you want. I chose an enum for explicitness. I also updated it to pass back a nullable date. This should correct your time issues, but you’ll need to account for null returned values.