1

私は現在、以下の関数を使用して、日付のリストから日付(今日)に最も近い日付を返しています。私の問題は、関数が今日の日付の過去または未来に関係なく、最も近い日付を返すことです。このコードを変更して、今日より後の最も近い日付と今日より前の最も近い日付を返すオプションがあるようにするにはどうすればよいですか?それは私からの地獄を混乱させています。

ご入力いただきありがとうございます。

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
4

2 に答える 2

2

このようにあなたが探しているものです。関数に何かを渡して、必要なものがわかるようにする必要があります。明示的に列挙型を選択しました。また、null許容の日付を返すように更新しました。これで時間の問題は修正されますが、nullの戻り値を考慮する必要があります。

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
于 2012-09-03T01:59:30.163 に答える
1

これをVB.Netに変換できることを願っています。アイデアは、日付を並べ替えてから、指定された日付のインデックスを見つけ、コレクション内の前の日付と次の日付がそれぞれ過去と未来に最も近いことです。

後の最も近い日付を見つける

string findNearestAfter(List<DateTime> ld, DateTime t)
{
    ld.Sort();

    int index = 0;
    for (int i = 0; i < ld.Count; i++ )
    {
        if (ld[i] == t)
            index = i;
    }

    string nearest = "";

    if (index < ld.Count)
        nearest = ld[index + 1].ToString();

    return nearest;
}

前に最も近い日付を見つける

string findNearestBefore(List<DateTime> ld, DateTime t)
{
    ld.Sort();

    int index = 0;
    for (int i = 0; i < ld.Count; i++ )
    {
        if (ld[i] == t)
            index = i;
    }

    string nearest = "";

    if (index > 0)
        nearest = ld[index - 1].ToString();

    return nearest;
}

ここに画像の説明を入力してください

上の画像から任意の日付を選択します。前と次が最も近い日付です。日付がソートされていることに注意してください。たとえば、8月の15を選択すると、最も近い将来の日付は21で、最も近い過去の日付は12です。

于 2012-09-03T01:50:07.033 に答える