30 December 2015

VB.NET: DateDiff for Weekdays Only


Here is a sample for calculating number of days within specific date range for weekdays only (exclude saturday and sunday) using Visual Basic .NET.

Design UI:

Code:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
        Label1.Text = "From:"
        Label2.Text = "To:"
        Label3.Text = "No. of Days:"
        Button1.Text = "Calculate Weekday"
    End Sub

    Public Shared Function
CalculateWeekdays(
ByVal startDate As Date, _
                          
ByVal endDate As Date) As Integer
        Dim numWeekdays As Integer
        Dim totalDays As Integer
        Dim WeekendDays As Integer
        numWeekdays = 0
        WeekendDays = 0

        totalDays = DateDiff(DateInterval.Day, startDate, endDate) + 1

        For i As Integer = 1 To totalDays

            If DatePart(DateInterval.Weekday, startDate) = 1 Then
                WeekendDays = WeekendDays + 1
            End If
            If
DatePart(DateInterval.Weekday, startDate) = 7 Then
                WeekendDays = WeekendDays + 1
            End If
            startDate = DateAdd("d", 1, startDate)
        Next

        numWeekdays = totalDays - WeekendDays

        Return numWeekdays
    End Function

    Private Sub
Button1_Click(ByVal sender As System.Object, _
               
ByVal e As System.EventArgs) Handles Button1.Click

        TextBox1.Text = CalculateWeekdays(DateTimePicker1.Value, _
                                          DateTimePicker2.Value)

    End Sub

End Class


Runtime:



Click here if you like this article.


0 comments: