How to calculate a date before a given date in unix?

I have two variables, X and Y.

The X value will be the date given in mmddyy format and I want to calculate the date before the date and so that it will be returned in yyyymmdd format.

Let me give you an example. When X = "091509" (mmddyy format) Y should be "20090914" (yyyymmdd format)

+2


source to share


4 answers


~$ date -d "20090101 -1 day"
Wed Dec 31 00:00:00 CET 2008

      

And if you want to get the date in a custom format, you just insert the formatted strings.

~$ date -d "2009-09-15 -1 day" +%Y%m%d
20090914

      



As for your conversion, you can use bash substring extraction (assuming you are using bash of course). It also assumes that your login is consistent and "secure".

X="091509"
Y=`date -d "${X:4:2}${X:0:2}${X:2:2} -1 day" +%Y%m%d`
echo $Y

      

See http://www.walkernews.net/2007/06/03/date-arithmetic-in-linux-shell-scripts/

+5


source


I like Tcl for date arithmetic, although it's clumsy for one-line wrappers. Using Tcl 8.5:



x=091509
y=$(printf 'puts [clock format [clock add [clock scan "%s" -format "%%m%%d%%y"] -1 day] -format "%%Y%%m%%d"]' "$x" | tclsh)

      

0


source


Since the -d option doesn't exist on MacOS X or FreeBSD, here is the answer for them

Getting a date relative to the current time

date -v -1d

      


For your question in particular, you need the -j and -f flags to use a specific date

date -v -1d -j -f %m%d%y 091509 +%Y%m%d

      

0


source


date -d "yesterday"

-1


source







All Articles