Minnu's Blog on Informatica & Data warehouse concepts

Archives

Monday, December 15, 2008

Unix Function to Substract 'N' days from a date

# Function to subtract N days from a YYYYMMDD date, Korn Shell
# * To subtract one day from a date, use
# new_date=$(DATE_MINUS '20000101' 1)
#
DATE_MINUS()
{
in_date=$1 # store input
in_year=${in_date%[0-9][0-9][0-9][0-9]} # extract YYYY
t=${in_date#[0-9][0-9][0-9][0-9]} # extract MMDD
in_mon=${t%[0-9][0-9]} # extract MM
in_day=${t#[0-9][0-9]} # extract DD

# add 0 to month (trick to make month an unpadded integer)
in_mon=`expr $in_mon + 0`

# subtract the required no. of days from the current day
in_day=`expr $in_day - $2`

# subtract months until day <= 0
while [ $in_day -le 0 ]
do
in_mon=`expr $in_mon - 1`

# if month is 0, then it is December of last year
if [ $in_mon -eq 0 ]; then
in_year=`expr $in_year - 1`
in_mon=12
fi

# add appropriate number of days to month
case $in_mon in
135781012) in_day=`expr $in_day + 31`;;
46911) in_day=`expr $in_day + 30`;;
2)
if [ `expr $in_year % 4` -eq 0 ]; then
if [ `expr $in_year % 400` -eq 0 ]; then
in_day=`expr $in_day + 29`
elif [ `expr $in_year % 100` -eq 0 ]; then
in_day=`expr $in_day + 28`
else
in_day=`expr $in_day + 29`
fi
else
in_day=`expr $in_day + 28`
fi
;;
esac
done

# the output is the formatted new value
printf "%.4d%.2d%.2d" $in_year $in_mon $in_day
}