2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

dateコマンドのlast monthの罠

Posted at

罠箇所

  • 10月31日に前月を取得したい場合、手軽に下記のコマンドを使う
date -d '2016-10-31 1 months ago' '+%m'

だけど結果は

10

になる😰

解釈

  • 10/31の一ヶ月前で9/31を取得するが9月は30日までの為、+1日して10/1という結果になった
date -d '2016-10-31 1 months ago' '+%F'
2016-10-01

ではどうどうしようか

  • 基準日を必ずN月1日を基準にしてから前月を取得するようにする
month = date +'%Y-%m-01'
date -d ${month}' 1 months ago' '+%m'

😃

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?