Get the yesterday’s date using shell script

To find yesterday’s date is easy if you have `GNU date’ installed:

$ date -d'yesterday'

But in other unixes (e.g. Solaris), there is no easy way out. I usually parse the date and minus one day of it. This method is error prone because my script will have to take care of month and year changes if the current date is the first day of the month. Don’t forget the special treatment required for leap years.

Today, I found a simpler workaround: TZ environment variable. Here’s how it works.

I’m living in “Asia/Kuala_Lumpur” and my time zone is GMT+8:00.
Current date time in my city:

$ date '+%Y/%b/%d %H:%M'

or specify the timezone explicitly:

$ TZ=Asia/Kuala_Lumpur date '+%Y/%b/%d %H:%M'

or specify the timezone in another format (maybe this is a unix specific format, note that it is -8 not +8):

$ TZ=GMT-8 date '+%Y/%b/%d %H:%M'

The output is:

2010/May/25 11:43

Current date time in Greenwich:

$ TZ=GMT date '+%Y/%b/%d %H:%M'

or

$ TZ=GMT+0 date '+%Y/%b/%d %H:%M'

The output is:

2010/May/25 03:43

Current date time in Costa Rica:

$ TZ=America/Costa_Rica date '+%Y/%b/%d %H:%M'

or

$ TZ=GMT+6 date '+%Y/%b/%d %H:%M'

The output is:

2010/May/24 21:43

Yesterday’s date in my city:

$ TZ=GMT+16 date '+%Y/%b/%d %H:%M'
2010/May/24 11:43

What is that `GMT+16‘? Here’s the trick. I try to ask the system to give me the date time for the timezone which is 16 hours to the west of Greenwich. And that “virtual” timezone is actually my city’s timezone.

This hack has its limitation:
1. It works for timezones to the east of Greenwich only.
2. It can only be used to look for yesterday’s date. You cannot use it to find the date 2 or more days ago. The N, in TZ=GMT+N, only accepts 0 to 24. If N is greater than 24, it will be treated as 24.

The same logic can be used to get the date of the next day. The only change is to replace GMT+N to GMT-N (replace plus with minus). Same limitations apply but this time it works only for the timezones to the west of Greenwich.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: