Thursday, 8 March 2012

Unix Shell Script - Get Tomorrows Date

This code snippet will calculate tomorrows date in the format DDMMYYYY. It takes into account correct monthly overlaps and leap years etc...


Code Snippet
  1.   # default output format, change as necessary
  2.   defaultof="%Y%m%d"
  3.  
  4.   # check for input format, else use default format,
  5.   # refer to 'man date' for help on format
  6.   # script only supports %Y %m %d at the moment
  7.   of=$defaultof
  8.   [ $# -eq 1 ] && of="$1"
  9.  
  10.   # get today's date
  11.   eval "`date +'y=%Y m=%m d=%d'`"
  12.  
  13.   #check for max number of days in current month
  14.   days=31
  15.   if [ $m -eq 4 ] || [ $m -eq 6 ] || [ $m -eq 9 ] || [ $m -eq 11 ] ; then
  16.     days=30
  17.   fi
  18.   # check for leap year if feb
  19.   if [ $m -eq 2 ]; then
  20.     days=28
  21.     leap1=`expr $y % 4`
  22.     leap2=`expr $y % 100`
  23.     leap3=`expr $y % 400`
  24.     if [ $leap1 -eq 0 ] ; then
  25.       if [ $leap2 -gt 0 ] || [ $leap3 -eq 0 ] ; then
  26.         days=29
  27.       fi
  28.     fi
  29.   fi
  30.  
  31.   # increment date
  32.   if [ $d -eq $days ]; then
  33.     d=1
  34.     m=`expr $m + 1`
  35.     if [ $m -eq 13 ]; then
  36.       m=1
  37.       y=`expr $y + 1`
  38.     fi
  39.   else
  40.     d=`expr $d + 1`
  41.   fi
  42.  
  43.   #Solaris date does not accept -d
  44.   #date -d "$y-$m-$d" +"$of"
  45.  
  46.   eval "y=`expr $y + 0` m=`expr $m + 0` d=`expr $d + 0`"
  47.   eval "y=`printf "%04d" $y` m=`printf "%02d" $m` d=`printf "%02d" $d`"
  48.   tomorrowsDate="${d}${m}${y}"
End of snippet

No comments: