LoginSignup
1
3

More than 1 year has passed since last update.

dateコマンドで、前月・当月・翌月の初日と最終日の取得

Last updated at Posted at 2021-12-30

はじめに

月次処理だと、前月・翌月の1日や、その月の最後の日が、必要になることがよくあります。
dateコマンドでそれらを取得する方法のまとめです。

過去記事の派生です。

当月

1日

これはフォーマットで日付部分を01にすればよいです。

$ date +%Y%m01" 

末日

「翌月の1日からマイナス1日」で取得します。
dateコマンドは、日付文字列を受け取れるので、それを利用します。

$ date -d "$(date '+%Y%m01') 1 month 1 day ago" "+%Y%m%d"

前月

1日

「当月の1日から1ヶ月前」でいけます。

$ date -d "$(date '+%Y%m01') 1 month ago" "+%Y%m%d" 

末日

$ date -d "$(date '+%Y%m01') 1 day ago" "+%Y%m%d"

翌月

1日

$ date -d "$(date '+%Y%m01') 1 month " "+%Y%m%d" 

末日

$ date -d "$(date '+%Y%m01') 2 month 1 day ago" "+%Y%m%d"

まとめと補足

みてのとおり、Nヶ月後、N日後であれば、 N month, N day を追加、マイナスなら、 agoをつければいいです。
フォーマットをかえれば、年月のところだけ取り出せます。

$ date "+%Y%m"                          
202112

また、Nヶ月後、Nヶ月前を取得した場合は、日付は1日にしてから、その操作をするといいです。

やるとわかるのですが、日付部分が翌月には存在しないとき(29,30,31日)に、1 monthをやると、繰り上げ的なことがされて、プラス一ヶ月とはならないです。

$ date -d "20210130 1 month" "+%Y%m%d"
20210302
1
3
0

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
3