Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Script for 3rd last month 1st date and 2nd last month of the last date

Status
Not open for further replies.

kandir

Programmer
Feb 17, 2010
4
IN
Hi,

COuld you pleas ehelp me how to get the 3rd last month's 1st date and 2nd last month of the last date through script.

Ex : - If today is the "1-Feb-2010" then I need the output like

Today is ---> 1-Feb-2010
First day of the 3rd last month --> 1-Nov-2009.
Last day of the 2nd last month --> 31-Dec-2009.

**************************************

I have written a script in the below format but it is failing in whenthe month is 1 (jan) and 3 (March).

Please help me.


day=1
month=01
year=2010

echo "Today is ---> "$day'-'$month'-'$year

lmonth=`expr $month - 2`

if test "$lmonth" = "0"
then
lmonth=12
year=`expr $year - 1`
fi

v_3rd_last_month=`expr $lmonth - 1`

lday=`cal $lmonth $year |awk '$0~/[0-9]/ {print $NF}'|tail -1`

echo "First day of the 3rd last month ---> " 01'-'$v_3rd_last_month'-'$year
echo "Last day of 2nd last month was ---> " $lday'-'$lmonth'-'$year
 
What about this ?
echo "Today is ---> "$day'-'$month'-'$year
lmonth=`expr $month - 2`
if test "$lmonth" -le "0"; then
lmonth=`expr $month + 10`
year=`expr $year - 1`
fi
lday=`cal $lmonth $year |awk '$0~/[0-9]/ {print $NF}'|tail -1`
echo "Last day of 2nd last month was ---> " $lday'-'$lmonth'-'$year
v_3rd_last_month=`expr $lmonth - 1`
if test "$v_3rd_last_month" -le "0"; then
v_3rd_last_month=`expr $lmonth + 11`
year=`expr $year - 1`
fi
echo "First day of the 3rd last month ---> " 01'-'$v_3rd_last_month'-'$year

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Format date without leading 0:

Code:
mon=$(date +%-m)

# Use modulo, to avoid negative months:

# +12-3 = +9
nmon=$(((mon+9)%12))

# Still, we need to avoid the month being 0: 

if (( nmon == 0 )) ; then nmon=12; fi
year=$(date +%y)
if (( nmon > 9 )) year=$((year-1)); fi 
# eval is outdated as backticks. 

# combined: 
LC_TIME="en_US.UTF-8" date +%d-%b-%Y -d "$(date +%Y)-10-01"
- STOP -
I remember a simpler approach:

Code:
echo "1-"$(date +%b-%Y -d "-3months")

don't visit my homepage:
 
Thanks you very much for your help on this.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top