Thursday, April 23, 2020

datediff bash function

Datediff function to return the number of days between two dates.  It's not too robust, but I got it working on MacOS and Linux, mostly to accommodate the differences between GNU Util date and HomeBrew BSD date...

datediff() {
    date --version >> /dev/null 2>&1
    RETVAL=$?
    if [ -e /usr/local/bin/gdate ] && [ $RETVAL -ne 0 ] ;
    then
        DATEBIN=/usr/local/bin/gdate
    else
        DATEBIN=`which date`
    fi

    d1=$($DATEBIN -d "$1" +%s)
    d2=$($DATEBIN -d "$2" +%s)
    echo $(( (d1 - d2) / 86400 )) days
}

GNU date in MacOS

The GNU date utility is provided in the HomeBrew package coreutils as gdate.  Install with HomeBrew.

[~]
scott@bargamac$ HOMEBREW_NO_AUTO_UPDATE=1 brew install coreutils
==> Downloading https://homebrew.bintray.com/bottles/coreutils-8.32.mojave.bottle.tar.gz
==> Downloading from https://akamai.bintray.com/5d/5da6cb9dbc0a8144480dde2fb78eb0a5a1710490afc3697174f7e261ec69763f?__gda__=exp=1587689482~hmac=42c0483b851c
######################################################################## 100.0%
==> Pouring coreutils-8.32.mojave.bottle.tar.gz
==> Caveats
Commands also provided by macOS have been installed with the prefix "g".
If you need to use these commands with their normal names, you
can add a "gnubin" directory to your PATH from your bashrc like:
  PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
==> Summary
🍺  /usr/local/Cellar/coreutils/8.32: 476 files, 8.8MB


Note the path to all the coreutils which can be added to your system $PATH