I have a Linux shell script that utilizes this call to retrieve the date from yesterday in YYYY-MM-DD format:
date -d "1 day ago" '+%Y-%m-%d'
It works most of the time, but it returned “2013-03-09” instead of “2013-03-10” when the script was run yesterday morning at 0:35 CDT.
It’s very likely that Daylight Saving Time (which began yesterday) is to blame. I’m presuming “1 day ago” is calculated by subtracting 24 hours, because 24 hours before 2013-03-11 0:35 CDT was 2013-03-09 23:35 CST, resulting in “2013-03-09.”
So, with bash on Linux, what’s a nice DST-safe approach to retrieve yesterday’s date?
Asked by Ike Walker
I believe this will work regardless of how often or when you run it…
date -d "yesterday 13:00" '+%Y-%m-%d'
Answered by tink
Date operates a little differently on Mac OSX:
date -v-1d +%F
For Last week
date -v-1w +%F
Answered by Aries
This should work as well, but it may be too much:
date -d @$(( $(date +"%s") - 86400)) +"%Y-%m-%d"
Answered by perreal
If you know the script will execute in the early hours of the day, you can just do
date -d "12 hours ago" '+%Y-%m-%d'
BTW, if the script runs every day at 00:35 (through crontab? ), you should consider what would happen if the DST changes during that hour; the script may not execute, or may run twice. However, modern cron implementations are pretty sophisticated in this area.
Answered by leonbloy
date -d "yesterday" '+%Y-%m-%d'
To put this to use later:
date=$(date -d "yesterday" '+%Y-%m-%d')
Answered by suresh Palemoni
Post is based on https://stackoverflow.com/questions/15374752/get-yesterdays-date-in-bash-on-linux-dst-safe