Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get yesterday's date in bash on Linux, DST-safe

Tags:

linux

bash

People also ask

How do I get the current date in YYYY-MM-DD format in Linux?

To format date in YYYY-MM-DD format, use the command date +%F or printf "%(%F)T\n" $EPOCHSECONDS . The %F option is an alias for %Y-%m-%d .

What is date +% s in bash?

date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds. date +%T.


I think this should work, irrespective of how often and when you run it ...

date -d "yesterday 13:00" '+%Y-%m-%d'

Under Mac OSX date works slightly different:

For yesterday

date -v-1d +%F

For Last week

date -v-1w +%F

This should also work, but perhaps it is too much:

date -d @$(( $(date +"%s") - 86400)) +"%Y-%m-%d"

If you are certain that the script runs in the first hours of the day, you can simply do

  date -d "12 hours ago" '+%Y-%m-%d'

BTW, if the script runs daily at 00:35 (via crontab?) you should ask yourself what will happen if a DST change falls in that hour; the script could not run, or run twice in some cases. Modern implementations of cron are quite clever in this regard, though.


Here a solution that will work with Solaris and AIX as well.

Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.

You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.

echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1

The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.

When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:

echo "$(TZ=GMT+30 date +%Y-%m-%d)
$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1