Recently I was asked about a way to calculate the number of week days between two dates. It is simple enough to get the total days by subtracting two dates and then using the resulting TimeSpan object. But what if you want to skip counting Saturday and Sunday? As far as I can tell there is no .NET method to accomplish this. Now watch, as soon as I post this someone will prove me wrong.

The technique I came up with is to start at the first date and get the day of the week for each consecutive day until the end date. If the day of the week is a weekend, don’t count it.

if ($d.DayOfWeek -notmatch "Sunday|Saturday") {

#if the day of the week is not a Saturday or Sunday

#increment the counter

$i++

}

...

This is a slightly different way of using a For loop and I got stuck at first until I realized I needed to manually set a new value for $d each time through. After the loop completes $i should be the total number of weekdays. Here’s what my complete function looks like.

Function Get-TotalWeekDays {

<#

.Synopsis

Get total number of week days

.Description

Return the number of days between two dates not counting Saturday

and Sunday.

.Parameter Start

The starting date

.Parameter End

The ending date

.Example

PS C:\> Get-TotalWeekDays -start 7/1/2012 -end 7/31/2012

22

.Inputs

None

.Outputs

Integer

#>

[cmdletbinding()]

Param (

[Parameter(Position=0,Mandatory=$True,HelpMessage="What is the start date?")]

[ValidateNotNullorEmpty()]

[DateTime]$Start,

[Parameter(Position=1,Mandatory=$True,HelpMessage="What is the end date?")]

[ValidateNotNullorEmpty()]

[DateTime]$End

)

Write-Verbose -message "Starting $($myinvocation.mycommand)"

Write-Verbose -Message "Calculating number of week days between $start and $end"

#define a counter

$i=0

#test every date between start and end to see if it is a weekend

for ($d=$Start;$d -le $end;$d=$d.AddDays(1)){

if ($d.DayOfWeek -notmatch "Sunday|Saturday") {

#if the day of the week is not a Saturday or Sunday

#increment the counter

$i++

}

else {

#verify these are weekend days

Write-Verbose ("{0} is {1}" -f $d,$d.DayOfWeek)

}

} #for

#write the result to the pipeline

$i

Write-Verbose "Ending $($myinvocation.mycommand)"

} #end function

The function is pretty easy to use: provide a start and end date and it will write the number of days to the pipeline.

22

Download Get-TotalWeekDays and let me know what you think.