Operating System - HP-UX
1751934 Members
4991 Online
108783 Solutions
New Discussion юеВ

Re: assign yesterday's date in ksh

 
satheeshnp
Advisor

assign yesterday's date in ksh

I have a requirement to assign yesterday's date in to a var.This should be compatible with all the months from Jan to Dec.

I am using ksh. whether there is any command
4 REPLIES 4
Anshumali
Esteemed Contributor

Re: assign yesterday's date in ksh

Below should be helpful, many examples:
http://forums11.itrc.hp.com/service/forums/questionanswer.do?threadId=9251
Dreams are not which you see while sleeping, Dreams are which doesnt allow you to sleep while you are chasing for them!!
James R. Ferguson
Acclaimed Contributor

Re: assign yesterday's date in ksh

Hi:

# YESTERDAY=$(perl -MPOSIX -le 'print strftime "%b %e",localtime(time-(60*60*24))')

# echo "${YESTERDAY}"
Oct 17

This will compute yesterday's date in your local timezone.

The Perl POSIX module allows you to use the 'strftime()' function with the same formatting directives you find in its manpages [ 'strftime(3C)' ]. These directives are the same as you use with the 'date' command. The '%e' specification yields the day of the month with space fill whereas the '%d' uses zero-fill.

Regards!

...JRF...
mvpel
Trusted Contributor

Re: assign yesterday's date in ksh

A not-so-subtle way of saying scripts should be in Perl, not sh.

In order to do this in shell, I think you can manipulate the TZ variable - just add the proper number of hours to your current timezone offset, like so:

gbrhpq$ echo $TZ
EST5EDT
gbrhpq$ date
Wed Oct 20 18:02:19 EDT 2010
gbrhpq$ expr 5 + 18 + 1
24
gbrhpq$ TZ=EST24EDT
gbrhpq$ date
Tue Oct 19 23:08:09 EDT 2010
gbrhpq$

It looks like the trick is adding just enough hours to the timezone offset to take you back to sometime after 23:00 (11:00pm) the day before. If you add more, it goes back to the current date and time:

gbrhpq$ TZ=EST25EDT
gbrhpq$ date
Wed Oct 20 18:17:09 EDT 2010
gbrhpq$

I'm not sure if this will work at 7:00pm in the same way, though. We'll see...
James R. Ferguson
Acclaimed Contributor

Re: assign yesterday's date in ksh

Hi (again):

> A not-so-subtle way of saying scripts should be in Perl, not sh.

There was no subtle message in what I wrote. I wasn't invoking a holy war; rather I was pointing out a pitfall that isn't necessarily apparent at first blush.

> In order to do this in shell, I think you can manipulate the TZ variable

Sure, fraught with peril. Oddly, if you look at *my* response to this technique in the link that Anshumali posted in this thread, you will see *why* using the TZ variable is a slippery slope.

Regards!

...JRF...