PoshCode Logo PowerShell Code Repository

Get Time Between Dates by Dan In Philly 3 weeks ago
View followups from dfdsdf | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/6887"></script>download | new post

Provide a begin and end time frame (mm dd yyyy) and this will calculate the years, months and days between the two dates. This is NOT 100% accurate but it was close enough for what I was trying to do. Someone with better math skills should be able to improve the accuracy.

  1. Clear
  2. $start = Read-Host "Start date (mmddyyyy)"
  3.     $startY = $start.Substring(4,4)
  4.     $startM = $start.Substring(0,2)
  5.     $startD = $start.Substring(2,2)
  6.     $startDate = $startY+"-"+$startM+"-"+$startD
  7. $end = Read-Host "  End date (mmddyyyy)"
  8.     $endY = $end.Substring(4,4)
  9.     $endM = $end.Substring(0,2)
  10.     $endD = $end.Substring(2,2)
  11.     $endDate = $endY+"-"+$endM+"-"+$endD
  12.  
  13. $timespan = [datetime]$endDate - [datetime]$startDate
  14.  
  15. If($timespan.Days -gt 365) {[string]$yrs1 = $timespan.days/28/13}
  16.     Else { $yr1 = $timespan.Days / 365.25
  17.         $yrs1 = [string]$yr1 }
  18. $yrs2 = $yrs1.split(".")
  19. $Years = $yrs2[0]
  20. $mnth1 = "." + $yrs2[1]
  21. $mnth2 = [math]::Round($mnth1,5)
  22. If($timespan.Days -gt 365) {$mnth3 = $mnth2 * 13}
  23.     Else {$mnth3 = $mnth2 * 12}
  24. $mnth4 = [string]$mnth3
  25. $mnth5 = $mnth4.split(".")
  26. $Months = $mnth5[0]
  27. $days1 = "." + $mnth5[1]
  28. $days2 = [math]::Round($days1,5)
  29. If($timespan.Days -gt 365) {$Days = [math]::Truncate(($days2 * 24) - 1)}
  30.     Else {$Days = [math]::Round($days2 * 30)}
  31.  
  32. Write-Host $years "years, "$months "months, "$days "days"

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me