Skip to content

Instantly share code, notes, and snippets.

@amitsaurav
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitsaurav/8923443 to your computer and use it in GitHub Desktop.
Save amitsaurav/8923443 to your computer and use it in GitHub Desktop.
Get Previous Date in Bash
#!/bin/sh
year=`date +%Y`
month=`date +%m`
day=`date +%d`
isLeap=0
if [ $((year%400)) -eq 0 ]; then
isLeap=1
elif [ $((year%100)) -eq 0 ]; then
isLeap=0
elif [ $((year%4)) -eq 0 ]; then
isLeap=1
fi
if [ $day -eq 01 ]; then
if [ $month -eq 03 ] && [ $isLeap -eq 1 ]; then
prevDay=29
elif [ $month -eq 03 ] && [ $isLeap -eq 0 ]; then
prevDay=28
elif [ $month -eq 01 ] || [ $month -eq 02 ] || [ $month -eq 04 ] || [ $month -eq 06 ] || [ $month -eq 08 ] || [ $month -eq 09 ] || [ $month -eq 11 ]; then
prevDay=31
elif [ $month -eq 05 ] || [ $month -eq 07 ] || [ $month -eq 04 ] || [ $month -eq 10 ] || [ $month -eq 12 ]; then
prevDay=30
fi
if [ $month -eq 01 ]; then
prevMonth=12
prevYear=$((year-1))
else
prevMonth=$(echo $month | sed 's/^0//')
prevMonth=$((prevMonth-1))
if [ $prevMonth -lt 10 ]; then
prevMonth=0$prevMonth
fi
prevYear=$year
fi
else
prevDay=$(echo $day | sed 's/^0//')
prevDay=$((prevDay-1))
if [ $prevDay -lt 10 ]; then
prevDay=0$prevDay
fi
prevMonth=$month
prevYear=$year
fi
echo "Previous Date is: $prevMonth/$prevDay/$prevYear"
echo "Today's Date is: $month/$day/$year"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment