Skip to main content

Comparing two dates

Calculate the number of days between 2 dates

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

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))
}

# -s in sec. | -m in min. | -h in hours | -d in days (default)
dateDiff -s "2006-10-01" "2006-10-32"
dateDiff -m "2006-10-01" "2006-10-32"
dateDiff -h "2006-10-01" "2006-10-32"
dateDiff -d "2006-10-01" "2006-10-32"
dateDiff "2006-10-01" "2006-10-32"