两个日期之间的星期五数(vb.net)

时间:2018-11-17 02:04:48

标签: vb.net

我需要计算2个日期中的星期五数 我有:DateTimePicker1,DateTimePicker2,button1,TextBox1

大概是: 如果DateTimePicker1 = 1-1-2019“星期一” 和DateTimePicker2 = 6-1-2017“星期日” *按下按钮1时,TextBox1 = 1

我试试这个:

dim count as integer
dim I as integer

for i = DateTimePicker1.value.DayOfWeek To DateTimePicker.value.DayOfWeek
  if i = DayOfWeek.Friday Then
    count = count + 1
  end if
Next
TextBox1 = Count

2 个答案:

答案 0 :(得分:0)

这里的窍门是将.ToShortDateString与Do循环进行比较。摆脱了时间因素的干扰。

Private Sub OPCode2()
            Dim count As Integer
            Dim d As DateTime = DateTimePicker1.Value
            Dim strEndDate = DateTimePicker2.Value.ToShortDateString
            'This will count the start date if it is Friday but not the end date
            'If you need to add the end dat then use the .AddDays(1) on the DateTimePicker2
            Do Until d.ToShortDateString = strEndDate
                If d.DayOfWeek = DayOfWeek.Friday Then
                    count += 1
                End If
                d = d.AddDays(1)
            Loop
            TextBox1.Text = count.ToString()
    End Sub

答案 1 :(得分:0)

我不确定您是否真的尝试过自己的代码,因为我看到语法中有错误,甚至该方法也不正确。无论如何,您可以尝试以下方法:

Dim count As Integer = 0
Dim startDate As DateTime = DateTimePicker1.Value
Dim TotalDays As Long = DateDiff("d", DateTimePicker1.Value, DateTimePicker2.Value) + 1
For i As Long = 1 To TotalDays
    If startDate.DayOfWeek = DayOfWeek.Friday Then
        count += 1
    End If
    startDate = startDate.AddDays(1)
Next
TextBox1.Text = count.ToString()