動作確認済環境:Ubuntu 22, Oracle Linux 8
1. 主なパラメータ
| パラメータ | 意味 | 例 |
|---|---|---|
| %F | 日付(フル)、%Y-%m-%dと同じ | 2023-10-01 |
| %D | 日付(簡略)、%m/%d/%yと同じ | 10/01/23 |
| %Y | 年(4桁) | 2023 |
| %y | 年(2桁) | 23 |
| %m | 月 | 01~12 |
| %d | 日 | 01~31 |
| %H | 時 | 00~23 |
| %M | 分 | 00~59 |
| %S | 秒 | 00~60 |
| %T | 時刻、%H:%M:%Sと同じ | 13:50:20 |
| %A | 曜日(フル) | Sunday |
| %a | 曜日(簡略) | Sun |
| %Z | アルファベットのタイムゾーン略称 | JST |
| %:z | +hh:mm 数値タイムゾーン | +09:00 |
2. 日付の表示
yyyymmddの形式で表示:
$ date +"%Y%m%d"
20231001yyyy-mm-ddの形式で表示:(%Fは、%Y-%m-%dと同じ)
$ date +%F
2023-10-013. 時刻の表示
- 時:分:秒 の形式で表示: (%Tは、%H:%M:%Sと同じ)
$ date +'%F %T'
2023-10-01 00:00:084. 曜日の表示
- 曜日の略称: %a
$ date '+%F (%a)'
2023-10-01 (Sun)- 完全な曜日名: %A
$ date '+%F (%A)'
2023-10-01 (Sunday)5. タイムゾーンの表示
- アルファベットのタイムゾーン略称 (例: JST):%Z
$ date +%Z
JST- 数値形式のタイムゾーン (例: +09:00):%:z
$ date +%:z
+09:00- アメリカ西海岸の時刻を表示:
$ TZ='America/Los_Angeles' date
Sat Sep 30 08:00:37 PDT 2023- JST (日本標準時) を表示:
$ TZ='Asia/Tokyo' date
Sun Oct 1 00:02:01 JST 20236. 日付の計算
- 昨日の表示:
$ date --date '1 day ago' +%F
2023-09-30--date: -dと同じ
-1 day: 1 day agoと同じ
- 一か月前の日を表示:
$ date -d '1 month ago' +%F
2023-09-01- 翌日の表示:
$ date -d '+1 day' +%F
2023-10-02- 一年後の日を表示:
$ date -d '+1 year' +%F
2024-10-017. 月の最初と最後の日を表示
コマンド例:
# Last month:
last_month_01=$(date -d "`date +%Y%m01` -1 month" +%F)
last_month_99=$(date -d "`date +%Y%m01` -1 day" +%F)
# This month:
this_month_01=$(date +%Y-%m-01)
this_month_99=$(date -d "`date +%Y%m01` +1 month -1 day" +%F)
# Next month:
next_month_01=$(date -d "`date +%Y%m01` +1 month" +%F)
next_month_99=$(date -d "`date +%Y%m01` +2 month -1 day" +%F)
# Output
echo "Last month: $last_month_01 ~ $last_month_99"
echo "This month: $this_month_01 ~ $this_month_99"
echo "Next month: $next_month_01 ~ $next_month_99"
実行結果:
Last month: 2023-09-01 ~ 2023-09-30
This month: 2023-10-01 ~ 2023-10-31
Next month: 2023-11-01 ~ 2023-11-30以上