如何在两个日期之间找到周数

时间:2014-03-18 10:44:52

标签: vb.net date

如何在两个日期之间找到周的开始日期。

示例:

date1: 4th March 2014. 
date2: 18th March 2014. 

然后它应该返回开始日期的周列表 2014-03-03, 2014-03-10, 2014-03-17

2 个答案:

答案 0 :(得分:2)

首先,您想获得开始日期的第一天?这给出了您想要的列表:

Dim firstDate = New Date(2014, 3, 4)
Dim daysToFirstDay As Int32 = DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek - firstDate.DayOfWeek
firstDate = firstDate.AddDays(daysToFirstDay) ' -1 day in this case
Dim lastDate = New Date(2014, 3, 17)
Dim days As Int32 = (lastDate - firstDate).Days + 1 ' including last

Dim result As List(Of Date) = Enumerable.Range(0, days).
    Select(Function(d) firstDate.AddDays(d)).
    Where(Function(day) day.DayOfWeek = DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek).
    ToList()

使用LINQ在开始日期和结束日期之间创建一系列Date s。然后,它使用当前DateTimeFormatInfo's FirstDayOfWeek属性仅返回开始工作日。

答案 1 :(得分:0)

 Function GetWeekStartDates(startDate As Date, endDate As Date) As List(Of Date)
    Dim result As New List(Of Date)
    Dim checkDate = startDate
    Dim Is1stWeek As Boolean = True
    Do While checkDate <= endDate
        If checkDate.DayOfWeek = DayOfWeek.Monday Then
            result.Add(checkDate)
            If Is1stWeek Then Is1stWeek = False
        Else
            If Is1stWeek Then
                result.Add(checkDate.AddDays(-checkDate.DayOfWeek + 1))
                Is1stWeek = False
            End If
        End If
        checkDate = checkDate.AddDays(1)
    Loop
    Return result
End Function