Operating System - Linux
1752794 Members
5707 Online
108789 Solutions
New Discussion юеВ

Re: last day of previous month

 
viseshu
Frequent Advisor

last day of previous month

Hi all,
I need to get the last day and first day of previous month.Can you please help me out
7 REPLIES 7
James R. Ferguson
Acclaimed Contributor

Re: last day of previous month

Hi:

Since you don't offer what language you want to use (Perl, shell, awk), I'll offer the general outline.

If the current month is one (Januaray=1) then the previous month is twelve (December=12) and its last day is 31. Exit.

Otherwise subtract one from the current month and using the resulting value, index into an array of days-in-a-month. If you point to February, do a modulus 4 (year mod 4) and if the result is zero (0) the last day of February is incremeted by one to equal 29.

The first day of any month is a degenerate case --- its simply one (1). You didn't specify if you wanted the dayname (e.g. Tuesday), etc.

Regards!

...JRF...
viseshu
Frequent Advisor

Re: last day of previous month

JRF,
can you please put it in awk???
RAC_1
Honored Contributor

Re: last day of previous month

cal 10||grep -v '[a-zA-Z]'|head -1|awk '{print $1}'
cal 10|grep -v '[a-zA-Z]'|tail -1|awk '{print $NF}'

There is no substitute to HARDWORK
john korterman
Honored Contributor

Re: last day of previous month

Hi Viseshu,

for the last day of the previous month, a shell interpretation of mr. Ferguson:

#!/usr/bin/sh

CURRENT_MONTH=$(date +%m)

case "$CURRENT_MONTH" in
01|03|05|07|08|10|12)
PREV_LAST=31;;
04|06|09|11)
PREV_LAST=30;;
02)
CURRENT_YEAR=$(date +%Y)
if [ $(( ${CURRENT_YEAR} % 4)) = 0 ]
then
PREV_LAST=29
else
PREV_LAST=28
fi;;
esac
echo $PREV_LAST


regards,
John K.
it would be nice if you always got a second chance
RAC_1
Honored Contributor

Re: last day of previous month

corrections.

cal 10||egrep -v '^$|[a-zA-Z]'|head -1|awk '{print $1}'
cal 10|egrep -v '^$|[a-zA-Z]'|tail -1|awk '{print $NF}'
There is no substitute to HARDWORK
James R. Ferguson
Acclaimed Contributor

Re: last day of previous month

Hi (again):

Actually, there's a Perl one-liner that will accomodate you.

# perl -MDate::Calc=:all -le '$m=shift;$y=shift;print Days_in_Month($y,$m==1 ? 12:$m-1)'

...that is, pass the year and the current month for which you want the last day of the previous month:

# perl -MDate::Calc=:all -le '$m=shift;$y=shift;print Days_in_Month($y,$m==1 ? 12:$m-1)' 3 2004

...returns:

29

Regards!

...JRF...
Hein van den Heuvel
Honored Contributor

Re: last day of previous month

Here is a silly, brute-force, yet simple and effective, all awk solution:

--------------------------
BEGIN {
t = systime()
m = strftime("%m", t)
this_month = m
while (m == this_month) {
t = t - 86400
m = strftime("%m", t)
}
last_month = m
print "Last day last month = " strftime("%D", t)
while (m == last_month) {
t = t - 86400
m = strftime("%m", t)
}
t = t + 86400
print "First day last month = " strftime("%D", t)
}