Subtracting months from passed Date

Hi All,

I am getting a date from environment variable and want to do some processing by subtracting 2 months from the date passed through the environment variable.

I am trying the following syntax :

date_var=2014-08-31
 date_2M_ago='$date_var+"%d%m%y" --$date_var="2 months ago" '

If I am using the system date,the below syntax works fine :

date_2M_ago='date+"%d%m%y" --date="2 months ago" 

But I want 2 months to be subtracted from the date passed through the environment variable.

Please suggest the correct syntax.

With GNU date:

date_var='2013-08-31'
date_2m_ago=$(date -d "$date_var -2 months" +%Y-%m-%d)

HI Balaji,

Thanks for the reply. I have tried the below code, it's working fine for most of the dates but with few discrepancies.

 
 date_var=$1
 day_var=${date_var##*-}
 date_2m_ago=$(date -d "$date_var -2 months" +%Y-%m-%d)
 day_2m_ago=${date_2m_ago##*-}
 if [[ ${day_var} = ${day_2m_ago} ]]
 then 
 echo "same"
 else
 echo "difference"
 date_2m_ago=$(date -d "date_2m_ago -1 days" +%Y-%m-%d)
 echo $date_2m_ago
 fi
 

The date passed as input parameter will always be the end of the month date and I need the output to be 2 months prior to the input date but want the O/P to be the end of the month date.

The above code is giving me the following output :

I/P Actual O/P expected O/P
2014-02-28 --> 2013-12-28 2013-12-31
2014-04-30 --> 2014-03-01 2014-02-28
2014-09-30 --> 2014-07-30 2014-07-31

The above code is giving the correct o/p for the rest of the month end dates for year 2014.

Thanks for your help!

Try

date_var='2014-02-28'
date -d"$(date -d"$date_var -45days" +"%Y/%m/01 - 1day")" +"%Y-%m-%d"
2013-12-31