How can I print yesterday's or tomorrow's date? Updated: 07/31/01


From the command-line:
======================
[Using Perl]
To print yesterday's date:

$ perl -e
'@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],($T[5]+1900)%100)'

To print tomorrow's date:

$ perl -e
'@T=localtime(time+86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],($T[5]+1900)%100)'

[the TZ trick]
If the system is located WEST of the Greenwich Meridian (ie - in the
Americas), you can determine tomorrow's date by temporarily subtracting
24 hours from the timezone offset, like so:

$ offset=`echo $TZ | tr -d '[A-Z+]'`
$ new_offset=`echo $offset - 24 | bc`
$ TZ=`echo $TZ | sed "s/[+-]\{0,1\}[1-9][0-9]\{0,1\}/$new_offset/` \
date +%D

Unfortunately, in this part of the world, a similar method method cannot
be used to obtain yesterday's date, because, under HP-UX, the timezone
offset can not be greater than +24.

If the system is located EAST of the Greenwich Meridian (ie - in Europe),
you can determine yesterday's date by temporarily adding 24 hours to the
timezone offset, like so:

$ offset=`echo $TZ | tr -d '[A-Z+]'`
$ new_offset=`echo $offset + 24 | bc`
$ TZ=`echo $TZ | sed "s/[+-]\{0,1\}[1-9][0-9]\{0,1\}/$new_offset/` \
date +%D

Unfortunately, in this part of the world, a similar method method cannot
be used to obtain tomorrow's date, because, under HP-UX, the timezone
offset cannot be less than -24.

[GNU date]
The GNU date command has a powerful -d option that the HP-UX date command
does not have. You can do things like:

$ date -d yesterday
$ date -d '2 days ago'
$ date -d '1 week ago'
$ date -d tomorrow
$ date -d '2 days'
$ date -d '1 week'

GNU date is part of the GNU sh_utils package. You can grab precompiled
HP-UX binaries from the Liverpool archive.

Programmatically
================
You can write a simple (and portable) C program that does the job using
the good ol' time() function:

#include <time.h>
time_t today = time(null);
time_t yesterday = today - (time_t)(24 * 60 * 60);
time_t tomorrow = today + (time_t)(24 * 60 * 60);
char *date_yesterday = ctime(&yesterday);
char *date_tomorrow = ctime(&tomorrow);

NOTE: Daylight Savings Time causes problems with the above code, since
there are two days in the year when this program would fail due to
the fact that some days don't have 24 hours. Calling this program
early in the morning, the day after a 23-hour day, will give you
the day before yesterday. Calling this program late at night, on
a 25-hour day would give you the same day.



UNIXguide.net
English to Visayan Cebuano Dictionary
Suggest a Site
Visayan Cebuano to English Dictionary