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)
YEAR=$(date +%y)

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

This is a lot better:


(edited to correct link)

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: