Powershellで月初と月末を取得してみました。
Get-Date のメソッドを利用して取得できます。
また、取得した情報をISO 8601形式(YYYY-MM-DDTHH:MM:SS+HH:MM)のタイムゾーンを含む形式に成形してみました。
1.今月の月初・月末を取得する
1-1.月初(今月)
以下のコマンドで月初の日付を取得できます。
時分秒は指定しないと実行した時刻になるので0時0分0秒を指定しています。
# 現在の日付を取得
$today = Get-Date
# 今月の月初を取得
$biggining_of_month = Get-Date -Year $today.Year -Month $today.Month `
-Day 1 -Hour 0 -Minute 0 -Second 0
# 出力をフォーマット形式で表示
$biggining_of_month_date = $biggining_of_month.ToString("yyyy-MM-dd HH:mm:sszzz")
# 結果出力
$biggining_of_month_date
1-1-1.実行結果(月初(今月))
PS C:\> # 現在の日付を取得
PS C:\> $today = Get-Date
PS C:\>
PS C:\> # 今月の月初を取得
PS C:\> $biggining_of_month = Get-Date -Year $today.Year -Month $today.Month `
>> -Day 1 -Hour 0 -Minute 0 -Second 0
PS C:\>
PS C:\> # 出力をフォーマット形式で表示
PS C:\> $biggining_of_month_date = $biggining_of_month.ToString("yyyy-MM-dd HH:mm:sszzz")
PS C:\>
PS C:\> # 結果出力
PS C:\> $biggining_of_month_date
2025-09-01 00:00:00+09:00
1-2.月末(今月)
以下のコマンドで月末の日付を取得できます。
こちらも、時分秒は指定しないと実行した時刻になるので23時59分59秒を指定しています。
# 現在の日付を取得
$today = Get-Date
# 今月の月末を計算
$end_of_month = Get-Date -Year $today.Year -Month $today.Month `
-Day (Get-Date -Year $today.Year -Month $today.Month -Day 1).AddMonths(1).AddDays(-1).Day `
-Hour 23 -Minute 59 -Second 59
# フォーマット形式で結果を表示
$end_of_month_date = $end_of_month.ToString("yyyy-MM-dd HH:mm:sszzz")
# 結果出力
$end_of_month_date
1-2-1.実行結果(月末(今月))
PS C:\> # 現在の日付を取得
PS C:\> $today = Get-Date
PS C:\>
PS C:\> # 今月の月末を計算
PS C:\> $end_of_month = Get-Date -Year $today.Year -Month $today.Month `
>> -Day (Get-Date -Year $today.Year -Month $today.Month -Day 1).AddMonths(1).AddDays(-1).Day `
>> -Hour 23 -Minute 59 -Second 59
PS C:\>
PS C:\> # フォーマット形式で結果を表示
PS C:\> $end_of_month_date = $end_of_month.ToString("yyyy-MM-dd HH:mm:sszzz")
PS C:\>
PS C:\> # 結果出力
PS C:\> $end_of_month_date
2025-09-30 23:59:59+09:00
2.先月の月初・月末を取得する
上記と同じようなコマンドで取得可能です。
違いは「.AddMonths(-1)」を付けるかどうかです。
2-1.月初(先月)
# 現在の日付を取得
$today = Get-Date
# 先月の月初を取得
$biggining_of_last_month = Get-Date -Year $today.Year -Month $today.AddMonths(-1).Month `
-Day 1 -Hour 0 -Minute 0 -Second 0
# 出力をフォーマット形式で表示
$biggining_of_last_month_date = $biggining_of_last_month.ToString("yyyy-MM-dd HH:mm:sszzz")
# 結果出力
$biggining_of_last_month_date
2-2.月末(先月)
# 現在の日付を取得
$today = Get-Date
# 先月の月末を計算
$end_of_last_month = Get-Date -Year $today.Year -Month $today.AddMonths(-1).Month `
-Day (Get-Date -Year $today.Year -Month $today.Month -Day 1).AddMonths(1).AddDays(-1).Day `
-Hour 23 -Minute 59 -Second 59
# フォーマット形式で結果を表示
$end_of_last_month_date = $end_of_last_month.ToString("yyyy-MM-dd HH:mm:sszzz")
# 結果出力
$end_of_last_month_date