How to get yesterday and day before yesterday in l

2020-06-30 04:54发布

问题:

I want to get sysdate -1 and sysdate -2 in variable and echo it. I am using below query which gives todays date as output.

#! /bin/bash
tm=$(date +%Y%d%m)
echo $tm

How to get yesterday and day before yesterdays date?

回答1:

Here is another one way,

For yesterday,

date -d '-1 day' '+%Y%d%m'

For day before yesterday,

date -d '-2 day' '+%Y%d%m'


回答2:

  1. Yesterday date

    YES_DAT=$(date --date=' 1 days ago' '+%Y%d%m')
    
  2. Day before yesterdays date

    DAY_YES_DAT=$(date --date=' 2 days ago' '+%Y%d%m')
    

For any date you can use below one default it take 1 days. If its passing value that day before it take

ANY_YES_DAT=$(date --date=' $1 days ago' '+%Y%d%m')


回答3:

You can get the yesterday date by this:

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

and day before yesterday by this:-

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


回答4:

For older versions of BSD date (on old versions of macOS for example) which don't provide a -v option, you can get yesterdays date by subtracting 86400 seconds (seconds in a day) from the current epoch.

date -r $(( $(date '+%s') - 86400 ))

Obviously, you can subtract 2 * 86400 away for the day for yesterday etc.

Edit: Add reference to old macOS versions.



标签: linux shell unix