给定日期列表,如何获取过去到今天的最近日期,以及将来今天在VB.NET中的最近日期 [英] Given a list of dates, how do I get the nearest date in the past to today and the nearest date in the future to today in VB.NET

查看:116
本文介绍了给定日期列表,如何获取过去到今天的最近日期,以及将来今天在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

这篇关于给定日期列表,如何获取过去到今天的最近日期,以及将来今天在VB.NET中的最近日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆