Bash script to determine difference between dates

Viewing 0 reply threads
  • Author
    Posts
    • #2335
      Amit Bansal
      Keymaster

      This is simple bash script which I have created to get difference between 2 dates. Please feel free to comment on improving it further

       

      #!/bin/bash
      ##usage sh diff_days.sh date1 date2
      ##date format MMDDYYYY
      usage () {
      echo "usage:sh diff_days.sh date1 date2"
      echo "date format MMDDYYYY"
      exit 1
      }
      get_days() {
      l_date=$1
      l_mnth=`echo $l_date|cut -c1-2`;
      l_dt=`echo $l_date|cut -c3-4`;
      l_year=`echo $l_date|cut -c5-8`;
      l_days=0;
      t_days=0;
      #Month array
      month[1]="31";
      month[3]="31";
      month[4]="30";
      month[5]="31";
      month[6]="30";
      month[7]="31";
      month[8]="31";
      month[9]="30";
      month[10]="31";
      month[11]="30";
      month[12]="31";
      #To check leap year
       if [ $[$l_year % 400] -eq 0 -o \( $[$l_year % 4] -eq 0 -a $[$l_year % 100] -ne 0 \) ] ; then
       month[2]="29";
       else
       month[2]="28";
       fi
      
      for ((i=1;i<$l_mnth;i++))
      do
      l_days=`expr $l_days + ${month[$i]}`;
      done
      t_days=`expr $l_dt + $l_days`
      echo $t_days
      }
      verify_date() {
      local l_date=$1
      retcode=0
      if [ ${#l_date} -ne 8 ]; then
      retcode=1
      fi
      l_mnth=`echo $l_date|cut -c1-2`;
      l_dt=`echo $l_date|cut -c3-4`;
      l_year=`echo $l_date|cut -c5-8`;
      if [ $l_mnth -lt 1 -o $l_mnth -gt 12 ]; then
      retcode=1
      fi
      echo $retcode
      }
      
      l_date1=$1
      l_date2=$2
      check=`verify_date $l_date1`;
      [[ $check -eq 1 ]] && usage;
      check=`verify_date $l_date2`;
      [[ $check -eq 1 ]] && usage;
      get_year1=`echo $l_date1|cut -c5-8`
      get_year2=`echo $l_date2|cut -c5-8`
      get_day_of_yr1=`get_days $l_date1`;
      get_day_of_yr2=`get_days $l_date2`;
      diff_days=`expr \( $get_year1 - $get_year2 \) \* 365 + $get_day_of_yr1 - $get_day_of_yr2 `;
      echo $diff_days
Viewing 0 reply threads
  • You must be logged in to reply to this topic.