So I have a date range. dateFrom and dateTo. I want to count how many days from dateFrom and dateTo without weekend. Example : user select Thursday's date until next week Monday's date. So it should be only 3 days instead of 5 days. Next if user select Saturday's date to Sunday's date it'll be zero. Any ideas on how to do it? Thanks !
Edit : I have a way on to count the days but it's included the weekends date. So how to count it excludes the weekends ?
Private Function CalculateDaysBetweenDates() As Integer
Dim dateFrom As DateTime = Convert.ToDateTime(datepickerFrom.Date)
Dim dateTo As DateTime = Convert.ToDateTime(datepickerto.Date)
Dim ts As TimeSpan = dateTo.Subtract(dateFrom)
If Convert.ToInt32(ts.Days) > 0 Then
radHalfday.Enabled = False
radHalfday.Value = False
Else
radHalfday.Enabled = True
End If
Return 1
End Function
*please, help me...
CodePudding user response:
Please refer to the code below. :)
Private nBetweenDayCnt As Integer = 0
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
Dim datTim1 As Date = #7/21/2022#
Dim datTim2 As Date = #7/24/2022#
nBetweenDayCnt = 0
Dim i As Integer = 0
Dim temp As DateTime
While True
temp = datTim1.AddDays(i)
If temp.DayOfWeek <> DayOfWeek.Sunday AndAlso temp.DayOfWeek <> DayOfWeek.Saturday Then
nBetweenDayCnt = 1
End If
Dim Between As TimeSpan = datTim2 - temp
If Between.Days <= 0 Then
Exit While
End If
temp = datTim1.AddDays(i)
i = 1
End While
Debug.WriteLine(nBetweenDayCnt.ToString())
End Sub
CodePudding user response:
There is an edge case, same date, in this.
Private Function DaysBetween(dtFrom As Date, dtTo As Date) As Integer
Dim rv As Integer = 0
Dim dL As Date = If(dtFrom.Date <= dtTo.Date, dtFrom.Date, dtTo.Date)
Dim dH As Date = If(dtFrom.Date <= dtTo.Date, dtTo.Date, dtFrom.Date)
If dL <> dH Then 'dates different?
rv = CInt((dH - dL).TotalDays) 1 'incl. from and to
While dL <= dH
If dL.DayOfWeek = DayOfWeek.Saturday Then
rv -= 1
ElseIf dL.DayOfWeek = DayOfWeek.Sunday Then
rv -= 1
dL = dL.AddDays(5)
End If
dL = dL.AddDays(1)
End While
ElseIf dL.DayOfWeek >= DayOfWeek.Monday AndAlso dL.DayOfWeek <= DayOfWeek.Friday Then
'same date
'return 1 or 0(default) ??????????????????
' rv = 1
End If
Return rv
End Function