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 to share