How to get date n months before in Unix?

Hi,

I need the date n months before currrent date
I need to store date in a varible say x
and then get the date 6 month before and get the result in the format 25-Aug-2009

Please Advice

If you have GNU date you can do something like:

date -d "2 month ago" +%F

otherwise you can check one of the links of:

http://www.unix.com/answers-frequently-asked-questions/13785-yesterdays-date-date-arithmetic.html

Hi Franklin,

I have tried with the above command and the article too doesn't help in terms of finding the date n month before the current date. i am using AIX unix and the commands as mentioned for Free bSD and gnu dates aren't working.

Maybe there are shorter solutions with perl but with awk you can do something like this in your script:

x=11

newdate=$(echo $x | awk -v date="$(date "+%d %m %Y")" -v OFS="-" '
{ 
  num=$0
  split(date, a); d=a[1]; m=a[2]; y=a[3]
  m-=num
  while(m < 1) {m+=12; y--}
  printf("%02d%s%02d%s%s\n", d, OFS, m, OFS, y)
}')

echo $newdate

You can change the format in the printf statement, the variable OFS is the separator.
Play around with it to get the desired format.

There is a problem with the end of month. You would need to add some code so that the function doesn't return invalid dates like "31-Nov-2009".

Thanks a lot Franklin this is working fine!!

---------- Post updated at 05:49 AM ---------- Previous update was at 05:48 AM ----------

Ygor thanks for the input i am working on adding that check

Oops, right, it's much more complicated than that :smiley: but here we go:

x=11
newdate=$(echo $x | 
awk -v date="$(date "+%d %m %Y")" -v OFS="-"  '
{ 
  num=$0
  split(date, a); d=a[1]; m=a[2]; y=a[3]
  m-=num
  while(m < 1) {m+=12; y--}
  if(m == 2 && d >= 29){
    if((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)){
      d-=29
      m++
    }
    else {
      d-=28
      m++
    }
  }
  if(d == 31 && (m < 8 && m % 2 == 0) || m > 7 && m % 2 ) {
    d=1
    m++
  }  
  if(m > 12)y++
  while(m < 1) {m+=12; y--}
  printf("%02d%s%02d%s%s\n", d, OFS, m, OFS, y)
}')

echo $newdate

Thanks a lot Franklin!!!