There are actually many solutions to be found via Google, but here is one that I just stumbled across and like for its brevity. You would use its ansi_dn
function on both dates and calculate the difference.
diff_dates.sh
:
#!/bin/ksh
. ./ansi_dn.sh
date_to="$1"
date_from="$2"
echo $((
$(ansi_dn \
$(echo "${date_to}" | cut -d/ -f3) \
$(echo "${date_to}" | cut -d/ -f2) \
$(echo "${date_to}" | cut -d/ -f1) \
)
- $(ansi_dn \
$(echo "${date_from}" | cut -d/ -f3) \
$(echo "${date_from}" | cut -d/ -f2) \
$(echo "${date_from}" | cut -d/ -f1) \
)
))
(If you have the years, months and days of both dates in separate variables already the cut
nightmare is not needed, obviously.)
Example:
$ ./diff_dates.sh 08/05/2013 01/01/1939
27156
Let's verify correctness with GNU date
:
$ echo $(( ( $(date -d 2013-05-08 +%s) - $(date -d 1939-01-01 +%s) + 43200 ) / 86400))
27156