2011-12-20

bash: adding or subtracting days from a date

I had this problem at my workplace. As I crawled through the web I saw that this is a very common question and rookies are directed to a forum at www.unix.com where someone reimplemented the World (many calendar functions) in bash. His solution is a very long and complicated lib which is an overkill for this kind of tiny task we have at hand.

My solution

t_days=30            # I needed stuff from a this long period,
t_reftime=2011-11-14 # just before this date

# 1st: Translate the reference time to UNIX timestamp:
ts=`date --utc -d "$t_reftime" +%s`
# 2nd: Convert 30 days to seconds, subtract it from the above
# and add it to the UNIX epoch. Format as you like. I liked %Y-%m-%d
sdate=`date --utc -d "1970-01-01 $((ts-t_days*86400)) sec" +%Y-%m-%d`
# $sdate is now "2011-10-15"