Is there any way in Classic ASP VBScript to get the number of weekdays between 2 dates? Obviously, we have the DateDiff()
function but this will pull back the total
You're right, DateDiff()
doesn't cover this but it can be used in conjunction with WeekDay()
to work out if a Day
falls on a weekend.
By using DateDiff()
to get the number of days we can then use a For
loop to step through the days using DateAdd()
to increment the day as we go and check whether the incremented date value is a particular WeekDay()
. We can then decide based on this outcome whether to increment a counter that is storing our resulting number of weekdays.
Below is an example of how you would do this, the main logic has been encapsulated in a Function that you could include in a #include
script file to use in multiple pages.
<%
Function DateDiffWeekDays(d1, d2)
Dim dy: dy = 0
Dim dys: dys = DateDiff("d", d1, d2)
Dim isWeekDay: isWeekDay = False
Dim wkd
Dim wd: wd = 0
For dy = 0 To dys
wkd = Weekday(DateAdd("d", dy, d1))
isWeekDay = Not (wkd = vbSunday Or wkd = vbSaturday)
If isWeekDay Then wd = wd + 1
Next
DateDiffWeekDays = wd
End Function
'Example of how to call the function and output to the page
Call Response.Write(DateDiffWeekDays(Date(), CDate("12 Nov 2018")))
%>
Output:
16
This is just a quick example and doesn't cover every possible usage case, the idea is it gives you a starting point that you can work from and improve.
VBScript does not include the requested operation, but as DateDiff
with a ww
interval returns the number of Sundays between two dates, ensuring that start and end dates are out of the weekend we can directly calculate the number of working days:
Option Explicit
Function WorkingDaysBetween( ByVal d1, ByVal d2 )
Dim d
' Adjust date order to simplify calcs and always return 0 or positive number
If d1 > d2 Then
d = d1 : d1 = d2 : d2 = d
End If
' Move start date forward if it is a weekend
d = WeekDay( d1, vbMonday )
If d > 5 Then d1 = DateAdd( "d", 3-(d\6 + d\7), d1)
' Move end date backward if it is a weekend
d = WeekDay( d2, vbMonday )
If d > 5 Then d2 = DateAdd( "d", -1*(d\6 + d\7), d2)
' Calculate
' DateDiff("d") = Number of days between dates
' +1 to include start day
' -2 * DateDiff("ww") to exclude weekends between dates
WorkingDaysBetween = 1 + DateDiff("d", d1, d2, vbMonday) - 2*DateDiff("ww", d1, d2, vbMonday)
' If the result is negative, there are no working days between both dates
If WorkingDaysBetween < 0 Then WorkingDaysBetween = 0
End Function