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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get last month?

Status
Not open for further replies.

volcano

Programmer
Aug 29, 2000
136
HK
Hi, would you tell me how I can get the last month of the year? For example, now is 200401, my wanted value is 200312. I know that the code of getting last day can be :

TZ="$TZ+24"
export TZ
YESTERDAY=`date +%Y%m%d`

can getting last month be similar to this?

Thank you
 
A solution :
[tt]
year=`date +%Y`
year=`expr $year - 1`
last_month=${year}12
echo $last_month
[/tt]
The same with ksh
[tt]
last_month=$(( $(date +%Y) -1 ))12
echo $last_month
[/tt]

Jean Pierre.
 
Hi thanks for your reply. I am afraid I expressed a wrong meaning. I mean I want a value of the previous month compared to the current month. That's not the last month of my specific year. For example, today is 6 Feb 2004, then my wanted value is 200401. If today was 20 Jan 2005, then my wanted value was 200412.

Please help, thanks!
 
[tt]
year=`date +%Y`
month=`date +%m`
month=`expr $month - 1`
if [ $month -eq 0 ]
then
year=`expr $year -1`
month=12
fi
last_month=`printf "%04d%02d\n" $year $month`
echo $last_month
[tt]
Ksh
[tt]
typeset -Z4 year=$(date +%Y)
typeset -Z2 month=$(( $(date +%m) -1 ))
if [ $month -eq 0 ]
then
(( year -= 1 ))
month=12
fi
last_month=${year}${month}
echo $last_month
[tt]


Jean Pierre.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top