LoginSignup
1
1

More than 5 years have passed since last update.

Powershellにおける無効日付(2月31日など)の扱い

Posted at

こちらの記事のPowerShell版をやってみる。

$BaseDate = Get-Date -Year 2017 -Month 1 -Day 31

@(0..5) | %{$BaseDate.AddMonths($_).ToString("yyyy-MM-dd")}
Result
2017-01-31
2017-02-28
2017-03-31
2017-04-30
2017-05-31
2017-06-30

1/31に対して.AddMonths()していくと、各月末日が表示される。
が、これはnヶ月足したら、その月は31日がなかったので繰り上げている様子。

ので、1ヶ月づつ加算していくと、

$BaseDate = Get-Date -Year 2017 -Month 1 -Day 31
$tmpDate = $BaseDate

@(0..5) | %{
    $tmpDate.ToString("yyyy-MM-dd")
    $tmpDate = $tmpDate.AddMonths(1)
}
Result
2017-01-31
2017-02-28
2017-03-28
2017-04-28
2017-05-28
2017-06-28

2/28の翌月以降は各月28日になる。

各月末日が取りたい場合はこんな感じ?

$BaseDate = Get-Date -Year 2017 -Month 2 -Day 1

@(0..5) | %{($BaseDate.AddMonths($_)).AddDays(-1).ToString("yyyy-MM-dd")}
Result
2017-01-31
2017-02-28
2017-03-31
2017-04-30
2017-05-31
2017-06-30

参考

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1