VB.NET: DateDiff Menghitung Hari Kerja


Setelah menulis untuk versi Visual Basic 6, mungkin juga ada yang perlu menghitung jumlah hari kerja (weekday) dalam rentang waktu/tanggal tertentu tanpa menghitung hari sabtu dan minggu dalam versi 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.


Post a Comment

6 Comments

Unknown said…
mau nanya donk...
kalau mau DateTimePickter2 menjadi hasil akhirnya jd perhitungan antara DateTimePickter1 ditambah Textbox1.. klo begitu gmna ya..?
mohon batuanya....
rani said…
DateTimePicker2.Value = DateAdd(DateInterval.Day, CDbl(TextBox1.Text), DateTimePicker1.Value)

dengan syarat textbox1.text isinya berupa angka
Unknown said…
terimakasih @rani irsan tp ko saptu minggu tetep keitung sy coba rubah menggunakan CalculateWeekdays malah error..
rani said…
owh... ya maaf2 baru ngeh sama pertanyaan nya.
jawabannya rada panjang, rani jawab pake artikel aja yah
http://rani-irsan.blogspot.com/2016/05/vbnet-dateadd-menambah-hari-hanya.html
Unknown said…
ok termakasih banyak... jd terbantu banget.. skali lagi terimakasih :-)
Aa said…
Gimana cara ngitung jumlah hari yg lewat ya mbk, misal, ketika tgl 10/02/2019 + hari skg, jdi udh berapa hari terhitung nya