0
0

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.

✟【Bash】dateの-dにプラス・マイナスで期間指定した時のそれぞれの挙動

0
Posted at

やりたいこと

bashのdate関数に-dオプションで期間指定をし、
現在から任意の日付を取得したかったが挙動を勘違いしてちょっとはまったのでメモ

環境

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

やったこと

1か月前の日付を取得しようとdateの-dオプションに「"-1 months ago"」を指定していたが
これがマイナスのマイナスでプラスになり1か月未来の日付を取得していた
今回の場合、正しくは「"1 months ago"」とすべきであった

現在の日付

TIME_ZONE='Asia/Tokyo'
CURRENT_DATE=$(TZ=${TIME_ZONE} date '+%Y%m%d')
# ↓本日の日付
echo $CURRENT_DATE
+ echo 20201104

タイムゾーンを東京にしてdateを取得した結果、投稿日の2020/11/04となる

-d を正の値(1 months ago)で指定

PLUS_DATE=$(TZ=${TIME_ZONE} date '+%Y%m%d' -d "1 months ago")

# ↓指定した期間より前の日付
echo $PLUS_DATE
+ echo 20201004

単純に1か月前の2020/10/04となっている

-d を負の値("-1" months ago)で指定

MINUS_DATE=$(TZ=${TIME_ZONE} date '+%Y%m%d' -d "-1 months ago")

# ↓指定した期間より後の日付
echo $MINUS_DATE
+ echo 20201204

-dにマイナスの値を渡すと-1か月前となり「負×負=正」なので1か月後の2020/12/04となった

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?