Operating System - HP-UX
1833758 Members
2501 Online
110063 Solutions
New Discussion

How to get (date -1) for 1st day of every month

 
Fenglin
Regular Advisor

How to get (date -1) for 1st day of every month

Hi

I would like to know how to get date-1 for the 1st day of every month. For e.g,on 1st Feb, i want to get 20090131,on 1st Jan i want to get 20081231.

FYI, I am trying to write a script for that. Kindly give the necessary details.

Regards
Feng Lin
6 REPLIES 6
Dennis Handly
Acclaimed Contributor

Re: How to get (date -1) for 1st day of every month

Bill Hassell
Honored Contributor

Re: How to get (date -1) for 1st day of every month

Clay's script is awesome and can handle most every date computation. Here is a simple script to return the last day of the month:

MON=12
YR=2008
print $(cal $MON $YR) | awk '{print $NF}'

Just compute month - 1 and roll the year if month - 1 is less than 1. Handles all the dates in the past from year 1 to year 9999 (Gregorian). It works by stringing the cal output onto one line. Therefore, the last number on the line will always be the last day of the month:

print $(cal 1 2008)
January 2008 S M Tu W Th F S 1 2 ... 28 29 30 31

awk '{print $NF}' always returns the last space-delimited string on a line.


Bill Hassell, sysadmin
James R. Ferguson
Acclaimed Contributor

Re: How to get (date -1) for 1st day of every month

Hi:

Yet another way is to use Perl. In your shell script, do something like:

...
if [ "$(date '+%d') = 1 ]; then # First of month
YESTERDAY=$(perl -MPOSIX -le 'print strftime "%m/%d/%Y",localtime(time-86400)')
echo ${YESTERDAY}
fi

You can use the same formatting directives you use with the Unix 'date' command with the 'strftime' function in the Perl script.

The computations are done in Epoch seconds, so the value of 86400 seconds is one-day.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: How to get (date -1) for 1st day of every month

>JRF: so the value of 86400 seconds is one-day.

Instead of using large magic numbers, you might want to use smaller identifiable ones: 24*60*60
James R. Ferguson
Acclaimed Contributor

Re: How to get (date -1) for 1st day of every month

Hi:

> Dennis: Instead of using large magic numbers, you might want to use smaller identifiable ones: 24*60*60

And sometimes I do just that. You can see that my commentary noted, "The computations are done in Epoch seconds, so the value of 86400 seconds is one-day."

...JRF...
Dennis Handly
Acclaimed Contributor

Re: How to get (date -1) for 1st day of every month

>JRF: You can see that my commentary noted

Yes. But if you use 24*60*60 you may not have to have that comment. :-)