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 $newDateSample output:
Thursday, April 13, 2023Subtract days from the current date:
# Subtract 15 days from today
$pastDate = (Get-Date).AddDays(-15)
Write-Output $pastDateSample output:
Wednesday, March 20, 2023Calculate 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.DaysSample output:
14Deep 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
- PowerShell’s official documentation on
DateTimemethods: Microsoft Docs - DateTime Methods - More about PowerShell date arithmetic: PowerShell Date Arithmetic
- To dive into the history and intricacies of calendar systems relevant to date computations: The Calendar FAQ