Search code examples
vb.netssrs-2008

Count the number of weekdays between two dates in visual basic


I'm a SQL guy, but I need a function to calculate the number of weekdays between two dates in VB.NET. I don't need to worry about holidays. My attempts unfortunately have been futile. Much appreciated

This will go in custom code in Reporting Service 2008 R2.


Solution

  • Try this. I modified an existing function that I've been using. This will work in SSRS 2008. Note, that you can also write your code in C#, if you're more comfortable with that, and after deploying it, just reference the assembly from the report.1

    public Shared Function Weekdays(ByRef startDate As Date,  ByRef 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