Hi, i want to calculate elasped time in Mintues excluding after 6pm and the weekends. for instance i have a start time on 2013-01-11 2:37:20 PM and need to calculate the time difference with repect to current time(NOW) in minutes by satisfying above 2 conditions. i've been trying to do this for while and kind of lost now. any help greatly appericated. i've tried this but to exclude the weekend but it's not working as per expectation.

Edited 3 Years Ago by docgrid: give more details

Dim GetWorkdays As Integer
        Dim pend As Date
        Dim pstart As Date


        pstart = txtcheck.Text
        pend = txtCheckEnd.Text


        If Weekday(pend) = 7 Then
            GetWorkdays = 7 - Weekday(pstart) + 5 * (DateDiff("ww", pstart, Now) - 1) + Weekday(Now) - 2
            txtTT.Text = GetWorkdays
        Else
            GetWorkdays = 7 - Weekday(pstart) + 5 * (DateDiff("ww", pstart, Now) - 1) + Weekday(Now) - 1
            txtTT.Text = Val(GetWorkdays) * Val("7.5")
        End If

        this is to check only for weekdays but it doesn't work.

Try this:

    Dim pend As Date
    Dim pstart As Date
    pstart = txtcheck.Text
    pend = txtCheckEnd.Text
    Dim Getworkdays As Integer = GetInterval(pstart,pend)
    txtTT.Text = GetWorkdays.ToString()

    Function GetInterval(ByVal StartDate As DateTime, ByVal EndDate As DateTime) As Integer
        Dim Wkday As Integer = Weekday(EndDate)
        If Wkday = 7 Then
            EndDate = EndDate.Subtract(TimeSpan.FromDays(1))
        ElseIf Wkday = 1 Then
            EndDate = EndDate.Subtract(TimeSpan.FromDays(2))
        End If
        Dim Initial As TimeSpan = EndDate.Subtract(StartDate)
        If Initial.TotalDays > 7 Then
            Initial -= TimeSpan.FromDays(Int(Initial.TotalDays / 7) * 2)
        End If
        GetInterval = Int(Initial.TotalDays)+1
    End Function    

A suggestion if your dates are coming from user input I would suggest using a masked textbox. With that you can filter the input and validate it as the proper format.

Edited 3 Years Ago by tinstaafl

I didn't like the way I adjusted for the end date being on a weekend, so I re-wrote it:

    Function GetInterval(ByVal StartDate As DateTime, ByVal EndDate As DateTime) As Integer
        Dim Initial As TimeSpan = EndDate.Subtract(StartDate)

        Dim Wkday As Integer = Weekday(EndDate, FirstDayOfWeek.Monday)
        If Wkday > 5 Then
            Initial -= TimeSpan.FromDays((7 - Wkday) + 1)
        End If
        If Initial.TotalDays > 7 Then
            Initial -= TimeSpan.FromDays(Int(Initial.TotalDays / 7) * 2)
        End If
        GetInterval = Int(Initial.TotalDays)
    End Function
This article has been dead for over six months. Start a new discussion instead.