LoginSignup
2
0

More than 1 year has passed since last update.

Linux: 曜日情報を取得する方法

Posted at

たまに必要となるのでメモ。

実施環境:
Linux
[testuser@testhost ~]$ uname -a
Linux testhost 4.18.0-147.8.1.el8_1.x86_64 #1 SMP Thu Apr 9 13:49:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
[testuser@testhost ~]$ echo $SHELL
/bin/bash

曜日によって実施する処理を変える等、曜日情報を取得したい場合はたまに存在します。
そのような場合は、dateコマンドのフォーマットに特定の文字列を指定することで取得できます。

%wを指定した場合、日曜日から0,1,2,3,4,5,6となる数値情報で取得できます。

Linux
[testuser@testhost ~]$ date
Tue Jul 13 21:44:44 JST 2021
[testuser@testhost ~]$ date +"%w"
2
[testuser@testhost ~]$ date -d "sunday" +"%w"
0
[testuser@testhost ~]$ date -d "monday" +"%w"
1
[testuser@testhost ~]$ date -d "saturday" +"%w"
6

%uを指定した場合、月曜日から1,2,3,4,5,6,7となる数値情報で取得できます。

Linux
[testuser@testhost ~]$ date
Tue Jul 13 21:48:25 JST 2021
[testuser@testhost ~]$ date +"%u"
2
[testuser@testhost ~]$ date -d "sunday" +"%u"
7
[testuser@testhost ~]$ date -d "monday" +"%u"
1
[testuser@testhost ~]$ date -d "saturday" +"%u"
6

文字列で取得したい場合は、%aまたは%Aを指定します。
ここで表示される文字列は、ロケール設定に依存します。

Linux
[testuser@testhost ~]$ date
Tue Jul 13 21:51:34 JST 2021
[testuser@testhost ~]$ date +"%a"
Tue
[testuser@testhost ~]$ date +"%A"
Tuesday
2
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
2
0