5
8

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 でタイムスタンプを扱う

Posted at

Bash でタイムスタンプや、その比較を行いたかったが、やり方を知らないことに気づいたので、焦らずしっかり調べて理解する。

現在の時間の取得

date コマンドは現在時間を取得する。

$ date
Fri Apr 17 14:54:18 PDT 2020

上記のは現在のタイムゾーンの値であるので、大小比較が可能な、1970-01-01 00:00:00 UTC からの経過秒数に変換します。%s がそれを表す記号ですので、`date "+フォーマット" の形式で形式をしていして表示できます。

$ date "+%s"
1587160470

Date のフォーマット

$ date "+%m/%d/%Y %H:%M"
04/17/2020 15:01

現在時のフォーマットはこれでよいですが、特定の文字列のフォーマットから違うフォーマットに変換する場合は、--date もしくは -d の引数で文字列を渡すとよいです。

$ date -d "04/17/2020 15:10"    
Fri Apr 17 15:10:00 PDT 2020
$ date -d "04/17/2020 15:10" "+%m/%d/%Y %H:%M"
04/17/2020 15:10

%s からのフォーマット

ただし、文字列ではなく、1970-01-01 00:00:00 UTC からの経過秒数 から変換をかけたい時は@を添付します。

date --date @1269553200 "+%m/%d/%Y %H:%M"
03/25/2010 14:40

大小の比較

タイムスタンプの大小比較は、1970-01-01 00:00:00 UTC からの経過秒数で比較するのがよさそうです。単純に比較するとよいです。結果も予想通り。ちなみに、Bashで数値の計算をしたいときは、$((計算)) になります。

test.sh

# !/bin/bash

last=$(date "+%s")

sleep 1

current=$(date "+%s")

if [ $current -gt $last ]; then 
        s=$((current - last))
   echo "current is bigger than Last: difference: ${s} sec."
else
   s=$((last - current))
   echo "Last is bigger than Current: difference: ${s} sec."
fi

結果は想定の通りです。

$./test.sh 
current is bigger than Last: difference: 1 sec.
5
8
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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?