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 1 year has passed since last update.

シェルスクリプトでUnixタイムを生成、解析(複合)する基本的なコマンドについて

Posted at

Unixタイム(エポックタイムとも呼ばれます)は、1970年1月1日のUTCから経過した秒数で、シェルスクリプトやその他のプログラミングでよく使用されます。ここでは、シェルスクリプトでUnixタイムを生成、解析(複合)する基本的なコマンドについて説明します。

Unixタイムの生成

現在のUnixタイムを生成するには、date コマンドを使用します。

# 現在のUnixタイムを取得
current_unix_time=$(date +%s)
echo $current_unix_time

指定した日時からUnixタイムを生成

特定の日時からUnixタイムを生成するには、date コマンドに -d オプション(GNU date)または -j オプション(BSD date)を使用して、日時を指定します。

# GNU dateの例(Linux等)
unix_time=$(date -d '2023-01-01 12:34:56' +%s)
echo $unix_time

# BSD dateの例(macOS等)
unix_time=$(date -j -f "%Y-%m-%d %H:%M:%S" "2023-01-01 12:34:56" +%s)
echo $unix_time

Unixタイムの解析(日時への変換)

Unixタイムを人が読める形式の日時に変換するには、再び date コマンドを使用します。このとき、-d オプション(GNU date)または -r オプション(BSD date)を使ってUnixタイムを指定します。

# GNU dateの例(Linux等)
unix_time=1672410296
readable_date=$(date -d @$unix_time)
echo $readable_date

# BSD dateの例(macOS等)
unix_time=1672410296
readable_date=$(date -r $unix_time)
echo $readable_date

これらのコマンドはシェルスクリプトで簡単に使用でき、Unixタイムを生成したり、Unixタイムから日時を得たりする場合に非常に便利です。ただし、date コマンドのオプションはOSによって異なる場合があるので、使用するシステムの date マニュアルを参照することをお勧めします。

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?