查找特定日期所在的连续日期范围

时间:2016-05-20 13:31:56

标签: vb.net date

给出一个日期范围列表......我们将调用empTimeOffPeriods

  

2016年6月2日,2016年6月3日,2016年4月4日   2016年6月8日,2016年6月9日,2016年6月6日,2016年6月11日

我需要找到特定日期(empRequestedOffDate)属于哪个连续日期范围

所以,

2016年6月4日将在6/2 / 2016-6 / 4/2016范围内下降

2016年6月9日将在6/8 / 2016-6 / 11/2016范围......等等。

我的empTimeOffPeriodsis已经排序。

我在VB.net中这样做

'Find all approved future events for team employee
empPtoDates = EventsManager.GetEventPaidTimeOffList(empDTO.UserId).FindAll(Function(x) x.EventDate >= DateTime.Today And x.Status = 1)

empOverLappingDates = empPtoDates.**'NOT SURE WHAT TO DO HERE**

'Build "EventType: (PeriodStart-PeriodEnd)"
If empPtoDates.Count > 0 Then
stbEventRanges.Append(empEvent).Append(": ")
                                stbEventRanges.Append(empOverLappingDates.First.EventDate.ToShortDateString()).Append("-")
                                stbEventRanges.Append(empOverLappingDates.Last.EventDate.ToShortDateString())
End If

1 个答案:

答案 0 :(得分:0)

所以,这是我的解决方案

Public Function FindDateRanges(ByRef listOfDates As List(Of DateTime)) As List(Of DefinedDateRange)

        'Find approved date ranges
        Dim DateRange = New DefinedDateRange(Nothing)
        Dim DefDateRanges As New List(Of DefinedDateRange)
        If listOfDates.Count > 0 Then
            DateRange = New DefinedDateRange(listOfDates(0), listOfDates(0)) 'First start/end date
            If listOfDates.Count > 1 Then 'Only one time off date in list

                For index As Integer = 1 To listOfDates.Count - 1
                    If listOfDates(index) = listOfDates(index - 1).AddDays(1) Then
                        DateRange.dtEnd = listOfDates(index)
                    Else
                        DefDateRanges.Add(DateRange)
                        DateRange = New DefinedDateRange(listOfDates(index), listOfDates(index)) 'Next Start/end date
                    End If
                Next
                DefDateRanges.Add(DateRange)

            Else
                DefDateRanges.Add(DateRange)
            End If
        End If
        Return DefDateRanges

    End Function

    Class DefinedDateRange
        Public dtStart As DateTime, dtEnd As DateTime

        Public Sub New(dateStart As DateTime, Optional dateEnd As DateTime = Nothing)
            Me.dtStart = dateStart
            Me.dtEnd = dateEnd
        End Sub
    End Class