Finding Dates Between Two Dates

by Jul 7, 2014

If you must know how many days are between two dates, you can easily find out by using New-TimeSpan:

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
$difference.Days

However, if you do not just want to know how many days there are, but if you actually need the exact days, here is another approach:

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
$days = [Math]::Ceiling($difference.TotalDays)+1

1..$days | ForEach-Object {
  $startdate
  $startdate = $startdate.AddDays(1)
}

This time, PowerShell outputs all dates between the two specified dates.

Since you now know the exact dates (and not just the number of days), you can filter, for example by weekday name, and find out how many Sundays or how many work days there are before you can go on vacation or retire.

This gives you just the working days:

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
$difference.Days

$days = [Math]::Ceiling($difference.TotalDays)+1

1..$days | ForEach-Object {
  $startdate
  $startdate = $startdate.AddDays(1)
} |
  Where-Object { $_.DayOfWeek -gt 0 -and $_.DayOfWeek -lt 6}

And this counts the working days:

$startdate = Get-Date
$enddate = Get-Date -Date '2014-09-12'

$difference = New-TimeSpan -Start $startdate -End $enddate
"Days in all: " + $difference.Days

$days = [Math]::Ceiling($difference.TotalDays)+1

$workdays = 1..$days | ForEach-Object {
  $startdate
  $startdate = $startdate.AddDays(1)
} |
  Where-Object { $_.DayOfWeek -gt 0 -and $_.DayOfWeek -lt 6} |
  Measure-Object |
  Select-Object -ExpandProperty Count

"Workdays: $workdays"

Twitter This Tip! ReTweet this Tip!