Thursday, May 1, 2008

Days Between

A little script to tell you the days between two YYYYMMDD dates:

#!/bin/bash

function usage {
  echo "date {date} {date}, where date is in the format YYYYMMDD"
}

function absolute_value {
  echo $1 | sed s/-//
}

# Print help, if number of args wrong

if [ -z $2 ]
then
  usage 1>&2
  exit 1
fi

if [ $3 ]
then
  usage 1>&2
  exit 1
fi

# The dates we want to days between
DATE_ONE="$1"
DATE_TWO="$2"

# provide the original date instead of "now" and ask for "seconds since epoch"

DATE_ONE_EPOCH=$(date -d "${DATE_ONE}" "+%s")
DATE_TWO_EPOCH=$(date -d "${DATE_TWO}" "+%s")

#Math

DAYS=$(($((${DATE_ONE_EPOCH} - ${DATE_TWO_EPOCH}))/$((60*60*24))))

absolute_value $DAYS

------

Note the unmath in "absolute_value" ;-)