Scripting Tip – Calculating Yesterday’s Date

Here’s a tip I picked up off rhaen’s blog for setting a date command for the previous day: use a different timezone.

$ echo $(TZ=CEST23CEST date)

He explains: ‘We use the environment variable TZ (timezone) to set a timezone which is 23 hours before our current timezone. As we don’t use EXPORT to set the timezone the environment is changed just for the only command. This is an easy way to get 23 hours back, plenty of time for your cronjob needs. The same method works on every timezone, of course.’

It’s much neater than my twisted solution using an offset (which isn’t adequate when yesterday is the end of month/year):

MONTH=$(date +%m)
DAY=$(date +%d)
OFFSET=${1:-1}
YEAR=$(date +%y)
YESTERDAY=$((DAY - OFFSET))

And then on and on, adjusting everything else for end of month or year.

This is a lot better:

YESTERDAY=$(TZ=CEST23CEST date +%Y%m%d)

(edited to correct link)

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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: