给定日期列表,如何获取过去到今天的最近日期,以及将来今天在VB.NET中的最近日期
我目前正在使用以下功能将最近的日期从日期列表返回到今天(今天)。我的问题是,函数返回最近的日期,不管它是过去还是将来的日期。如何更改此代码,以便在今天之前和之前的最近日期之前返回最近的日期?
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.
非常感谢您的输入。
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.
Public Enum DateCompare
LessThanEqualTo
GreaterThanEqualTo
End Enum
Public Function GetNearestDate(ByVal source As IEnumerable(Of DateTime), _
ByVal target As DateTime, _
ByVal dt As DateCompare) As Nullable(Of DateTime)
Dim result As Nullable(Of DateTime) = Nothing
Dim lowestDifference As TimeSpan = TimeSpan.MaxValue
Dim difference As TimeSpan
For Each _date As DateTime In source
If dt = DateCompare.LessThanEqualTo And _date > target Then
Continue For
ElseIf dt = DateCompare.GreaterThanEqualTo And _date < target Then
Continue For
End If
If target > _date Then
difference = target - _date
Else
difference = _date - target
End If
If difference < lowestDifference Then
lowestDifference = difference
result = _date
End If
Next
Return result
End Function