2015年8月21日金曜日

FreeBSDでunixtimeと日付表示を相互に変換する

必要があってFreeBSDでunixtimeと日付表示を相互に変換する必要があったので、調べた結果を以下にメモします。

以下のWebサイトが正解でした。
2011年 03月 30日
[Mac OS X][bash]unixtime と日付の相互変換表示
http://xiaoxia.exblog.jp/12344121/
以下は抜粋
以下のように .bashrc あたりに書いておくと幸せ。
function ut2date {
 /bin/date -u -r $1 +"%Y/%m/%d %H:%M:%S UTC"
 /bin/date -r $1 +"%Y/%m/%d %H:%M:%S"
}
function date2ut {
 /bin/date -j -f "%Y/%m/%d %H:%M:%S" "$1" +%s
}

ロケールは現在の設定を使用。
date2ut のフォーマットは限定で。

実行結果
> ut2date 1234567890
2009/02/13 23:31:30 UTC
2009/02/14 08:31:30
> date2ut "2009/02/14 08:31:30"
1234567890
上記はMacOS Xが対象ですが、FreeBSD 9.1で試したところ、動作しました。
dateコマンドに与えているオプションは次のような意味です。

-r seconds
         Print the date and time represented by seconds
         seconds(秒 - Unix Time)を日時で表示する

-u     Display or set the date in UTC (Coordinated Universal) time.
         UTCで表示する

-f      Use input_fmt as the format string to parse the new_date provided
         rather than using the default [[[[[cc]yy]mm]dd]HH]MM[.ss] format.
         Parsing is done using strptime(3).
         入力となる日時の形式を指定する

 -j      Do not try to set the date.  This allows you to use the -f flag
          in addition to the + option to convert one date format to
          another.
          与えた引数の時刻に設定せず、-fオプションで指定した日時形式を
          +オプションで指定した形式に変換して表示する。