Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash logic for finding previous calendar day [duplicate]

Tags:

date

bash

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

I have tried the following

Today's date : 20130701 Expected Output : 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

Code3 :

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]

Code4 :

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

Output

20130701

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

OS Version : SunOS 5.10

like image 498
misguided Avatar asked Jan 13 '23 00:01

misguided


2 Answers

You probably have python.

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

Though, if date would support the -d flag, then that would be my preferred solution.

like image 168
Owen Avatar answered Jan 22 '23 05:01

Owen


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

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

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

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

Solaris (as of version 10) still ships with the ridiculously old ksh88 as its default ksh. You should be able to 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 available, 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've already said --date doesn't work, but for completeness: On systems using the GNU version of date, 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
like image 42
rob mayoff Avatar answered Jan 22 '23 05:01

rob mayoff