「PowerShell」AddYears、AddMonthsで日時を計算する方法

書式
$変数名 = Get-Date '日時の文字列’

年の計算
$変数名.AddYears(数字)

月の計算
$変数名.AddMonths(数字)

日の計算
$変数名.AddDays(数字)

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$target = Get-Date '2022/05/02 12:20:21'
# 1年前/後を求める
Write-Host($target.AddYears(1))
Write-Host($target.AddYears(-1))
# 1ヶ月前/後を求める
Write-Host($target.AddMonths(1))
Write-Host($target.AddMonths(-1))
# 1日前/後を求める
Write-Host($target.AddDays(1))
Write-Host($target.AddDays(-1))
$target = Get-Date '2022/05/02 12:20:21' # 1年前/後を求める Write-Host($target.AddYears(1)) Write-Host($target.AddYears(-1)) # 1ヶ月前/後を求める Write-Host($target.AddMonths(1)) Write-Host($target.AddMonths(-1)) # 1日前/後を求める Write-Host($target.AddDays(1)) Write-Host($target.AddDays(-1))
$target = Get-Date '2022/05/02 12:20:21'

# 1年前/後を求める
Write-Host($target.AddYears(1)) 
Write-Host($target.AddYears(-1)) 

# 1ヶ月前/後を求める
Write-Host($target.AddMonths(1)) 
Write-Host($target.AddMonths(-1)) 

# 1日前/後を求める
Write-Host($target.AddDays(1)) 
Write-Host($target.AddDays(-1))

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
PS C:\study\powershell> .\test.ps1
2023/05/02 12:20:21
2021/05/02 12:20:21
2022/06/02 12:20:21
2022/04/02 12:20:21
2022/05/03 12:20:21
2022/05/01 12:20:21
PS C:\study\powershell> .\test.ps1 2023/05/02 12:20:21 2021/05/02 12:20:21 2022/06/02 12:20:21 2022/04/02 12:20:21 2022/05/03 12:20:21 2022/05/01 12:20:21
PS C:\study\powershell> .\test.ps1
2023/05/02 12:20:21
2021/05/02 12:20:21
2022/06/02 12:20:21
2022/04/02 12:20:21
2022/05/03 12:20:21
2022/05/01 12:20:21

 

PowerShell

Posted by arkgame