Bash logic to search for the previous calendar day

I want to find out the last calendar day using bash.

I tried the following

Today the date: 20130701 Expected result: 20130630

Code1:

 myTime=`TZ=$TZ+24 date +'%Y%m%d'` echo $myTime 

Output

 20130629 

Code2:

 timeB=$(date +%Y%m) sysD=$(date +%d) sysD=$((sysD-1)) echo $timeB$sysD 

Output

 2013070 

Code 3:

 yest=$(date --date="yesterday") echo "$yest" 

Output

 date: illegal option -- date=yesterday usage: date [-u] mmddHHMM[[cc]yy][.SS] date [-u] [+format] date -a [-]sss[.fff] 

Code 4:

 $ date +%Y%m%d -d "yesterday" 

Output

20130701

None of them gave the correct result. Can anyone advise me on the correct way to get the desired results.

OS Version: SunOS 5.10

+4
source share
3 answers

The system in question is most likely Solaris. This will work on Solaris:

 TZ=GMT+24+<YOUR_LOCAL_TIME_ADJUSTMENT> date +'%Y%m%d' 

Edit: To account for DST (example for GMT + 11 / GMT + 10 with DST):

 actualdate=$(date +'%Y%m%d%H%M') nondstdate=$(TZ=GMT+11 date +'%Y%m%d%H%M') if [ $actualdate = $nondstdate ] ; then TZ=GMT+35 date +'%Y%m%d' else TZ=GMT+34 date +'%Y%m%d' fi 

Edit 2: Bullet check for random TZ and DST:

 gmthour=$(date -u +%k) localhour=$(date +%k) tz=$(( gmthour - localhour )) echo Your Timezone is $tz yesterdaytz=$(( 24 + tz )) echo the offset for yesterday is $yesterdaytz TZ=GMT+$yesterdaytz date +'%Y%m%d' 
+2
source

You probably have python.

 python -c "import datetime; print datetime.date.today () - datetime.timedelta (days=1)" 

Although, if the date supports the -d flag, then this would be my preferred solution.

+4
source

Based on the usage report, I don't think you are on OS X. If you are on OS X, you can use the -v flag, but only with respect to the current date / time:

 $ date +%Y%m%d 20130630 $ date -v-1d +%Y%m%d 20130629 

If you have ksh , you can use it. I am not sure of the full syntax, so I don’t know if you can specify a base date, but you can do it relative to today:

 $ ksh -c 'printf "%(%Y%m%d)T\n" yesterday' 20130629 

Solaris (since version 10) still ships with the ridiculously old ksh88 by default ksh . You should find ksh93 (which supports the above syntax) in /usr/dt/bin/ksh :

 $ /usr/dt/bin/ksh -c 'printf "%(%Y%m%d)T\n" yesterday' 20130629 

If you have tclsh , you can use it:

 $ echo 'puts [clock format [clock scan "yesterday"] -format %Y%m%d]' | tclsh 20130629 $ echo 'puts [clock format [clock scan "20130701 - 1 day"] -format %Y%m%d]' | tclsh 20130630 

You already said that --date does not work, but for completeness: on systems using the GNU date version, you can use --date or -d :

 $ date +%Y%m%d 20130630 $ date +%Y%m%d -d yesterday 20130629 $ date +%Y%m%d -d '-1 days' 20130629 $ date +%Y%m%d -d '20130701 - 1 day' 20130630 
+3
source

Source: https://habr.com/ru/post/1489011/


All Articles