如何在两个日期范围内查找所有星期一

时间:2015-10-23 06:20:19

标签: vb.net date datetime dayofweek

我试图在使用输入的日期范围内获取所有星期一日期的列表。我已经完成了大部分工作,但我们能够找到下一个关于如何在开始日期和结束日期之间添加星期一的循环并将它们放入列表框中。

这不是家庭作业,只是我和一位朋友正在努力教他更多关于VB的事情,因为我也是新手。

这就是我现在所拥有的。

Private Sub btnCountMondays_Click(sender As Object, e As EventArgs) Handles btnCountMondays.Click
    Dim startDate As Date
    Dim endDate As Date
    startDate = txtStartDate.Text
    endDate = txtEndDate.Text
    txtDaysBetween.Text = DateDiff("d", startDate, endDate)

    For monday As Integer = 0 To Val(txtDaysBetween.Text)
        If monday = 1 Then
            lstResultsBox.Items.Add()
        End If
    Next
End Sub

2 个答案:

答案 0 :(得分:0)

如果必须使用for循环,可以按照以下步骤进行操作

Private Sub btnCountMondays_Click(sender As Object, e As EventArgs) Handles btnCountMondays.Click
    Dim startDate As Date
    Dim endDate As Date
    startDate = CDate(txtStartDate.Text)
    endDate = CDate(txtEndDate.Text)
    Dim nDays As Long = DateDiff("d", startDate, endDate) + 1
    For i As Long = 1 To nDays
        If startDate.DayOfWeek = DayOfWeek.Monday Then
            lstResultsBox.Items.Add(startDate.ToString("dd-MM-yyyy"))
        End If
        startDate = startDate.AddDays(1)
    Next
End Sub

答案 1 :(得分:0)

获取2个日期之间所有星期一的日期列表。得到日期的愤怒。并在循环期间获得星期几

Dim dt1 As New DateTime(2012, 5, 1)
Dim dt2 As DateTime = DateTime.Now
Dim ddl As New List(Of String)()
While dt1 < dt2
    Dim dow As DayOfWeek = dt1.DayOfWeek
    'enum
    Dim str As String = dow.ToString()
    'string
    If str.ToLower() = "monday" Then

        ddl.Add(dt1.ToString("dd-MMM-yyyy"))
    End If


    dt1 = dt1.AddDays(1)
End While