I want to create a generic function to calculate dates. Here is my attempt.
The function should add or subtract years/months/days from either a specified date or today. I've got the "calculate from today" part working, but do not know how to calculate from a specified date.
Function Calculate-Date {
Param(
[parameter][string]$Date,
[parameter(Mandatory = $True)][int]$AddYears,
[parameter(Mandatory = $True)][int]$AddMonths,
[parameter(Mandatory = $True)][int]$AddDays)
If ($Date -eq $null) {
(Get-Date).AddYears($AddYears).AddMonths($AddMonths).AddDays($AddDays).ToString("yyyy-MM-dd")
}
Else {
$CalculateDate = Get-Date $Date
($CalculateDate).AddYears($AddYears).AddMonths($AddMonths).AddDays($AddDays).ToString("yyyy-MM-dd")
}
}
This works.
Calculate-Date -AddYears 0 -AddMonths 0 -AddDays 2
This throws an error.
Calculate-Date -Date "2021-01-01" -AddYears 0 -AddMonths 0 -AddDays 2
Edit: Thanks to everybody, I was not just only able to overcome the error, but also simplify my function and add some extra parameters that I thought might be useful.
Function Calculate-Date {
Param(
[datetime]$Date = (Get-Date), # default to now
[int]$AddYears,
[int]$AddMonths,
[int]$AddDays,
[string]$Format = 'yyyy-MM-dd', # default format, change as required
[string]$Culture = (Get-Culture) # default culture
)
$Date.AddYears($AddYears).AddMonths($AddMonths).AddDays($AddDays).ToString($Format, [CultureInfo]::CreateSpecificCulture($Culture))
}
The differences to my original code are
I removed [parameter] and [parameter(Mandatory = $True). To be honest, I thought [parameter(Mandatory = $True) was necessary for the year, month and day because I was unfamiliar with default values.
I thought it might be useful to add a format parameter so I could do things like extract the weekday (for example, "dddd") or add specific separators (for example "yyyy年m月d日").
Having done that, I thought it would be good to specifiy the output' language or "culture". So "Friday" could become "viernes" if I used "es-ES".
Assuming my extended version works on your PC, here are some examples.
Calculate-Date
Should return the current date formatted as "yyyy-MM-dd"
Calculate-Date -AddYears 1 -AddMonths -2 -AddDays 3
Add a year, subtract 2 months, and add 3 days, with the same default format
Calculate-Date -AddYears 1 -AddMonths -2 -AddDays 3 -Format 'dddd'
Returns the weekday
Calculate-Date -AddYears 1 -AddMonths -2 -AddDays 3 -Format 'dddd' -Culture 'es-ES'
Does the same in Spanish (if not already the default)