Unix date in Bash

Show yesterday's date:

$ date -d yesterday
$ date -d yesterday +%Y-%m-%d

Show the UNIX timestamp:

$ date +%s
$ date --utc +%s
$ date -d yesterday --utc +%s

Convert a date string to timestamp:

function date2stamp () {
date --utc --date "$1" +%s
}

Convert a timestamp to a date string:

function stamp2date () {
date --utc --date "1970-01-01 $1 sec" "+%Y-%m-%d %T"
}

Calculate a date difference:

function dateDiff () {
case $1 in
-s) sec=1; shift;;
-m) sec=60; shift;;
-h) sec=3600; shift;;
-d) sec=86400; shift;;
*) sec=86400;;
esac

dte1=$(date2stamp $1)
dte2=$(date2stamp $2)
diffSec=$((dte2-dte1))
if ((diffSec < 0)); then abs=-1; else abs=1; fi
echo $((diffSec/sec*abs))
}

发表留言

人生在世,错别字在所难免,无需纠正。