2012-09-03 47 views
1

我目前使用下面的函数从列表中返回最近的日期约会日期(今天)。我的问题是,该函数返回最近的日期,无论它是过去或今天的日期的未来。如何更改此代码,以便今天之后可以选择返回距离最近的日期和距离最近的日期?这让我很困惑。给定一个日期列表,我如何获得过去到今天的最近日期以及将来到今天最近的日期在VB.NET中

非常感谢您的意见。

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 

回答

2

似乎是这样的你正在寻找。你只需要能够将某些东西传递给该函数,以便知道你想要什么。我选择了一个明确的枚举。我也更新它以传回可空日期。这应该纠正你的时间问题,但是你需要考虑空返回的值。

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 
+0

嘿谢谢回复,但它似乎并没有为我工作,GreaterThanEqualTo的作品,但LessThanEqualTo似乎一直返回00:00:00,任何想法? – Nookster

+0

只是更新了我的文章 – UnhandledExcepSean

+0

非常感谢很多这个工程伟大 – Nookster

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; 
} 

enter image description here

从上面的图片,挑选任何日期,上一页和下一页是最近的最近日期日期。请注意日期已排序。例如,选择8月15日,那么最近的未来日期是21,最近的过去的日期是12

+0

您好,感谢您的回复,我这样做是使用在线工具,它没有给出任何错误,但是,它的回报是错误的值转换,未来的回报没有和prev似乎返回一个值,方式::(混淆我的地狱 – Nookster

+0

让我试试新版本:) – Nookster

+0

是的,似乎是同样的问题,它返回2008年的价值最近当在列表中有许多2012日期,并且它之前没有返回任何内容。 :( – Nookster

相关问题