Calculating a date in the future or past

PowerShell:
Calculating a date in the future or past

How to:

Add days to the current date:

# Add 10 days to today's date
$newDate = (Get-Date).AddDays(10)
Write-Output $newDate

Sample output:

Thursday, April 13, 2023

Subtract days from the current date:

# Subtract 15 days from today
$pastDate = (Get-Date).AddDays(-15)
Write-Output $pastDate

Sample output:

Wednesday, March 20, 2023

Calculate the difference between two dates:

# Difference between two dates
$date1 = Get-Date '2023-04-01'
$date2 = Get-Date '2023-04-15'
$diff = $date2 - $date1
Write-Output $diff.Days

Sample output:

14

Deep Dive

Once upon a time, programmers had to manually calculate dates using complex algorithms. Now, languages like PowerShell provide built-in functions like AddDays, AddMonths, making it almost trivial.

Alternatives:

While AddDays is handy, there are also functions like AddHours, AddMinutes, etc., for more granular control. Plus, you could use [datetime]::Today.AddDays(10) if you prefer a static approach.

Implementation details:

PowerShell’s DateTime object has these methods baked in, so you’re not reinventing the wheel. Under the hood, it’s handling all sorts of complexities like leap years and daylight saving adjustments for you.

See Also