How can I calculate the date preceding a given date in unix?

耗尽温柔 提交于 2019-12-31 02:42:25

问题


I have two variables: X and Y.

The value of X will be a date given in the format mmddyy and I want to calculate the date preceding that date and have it be returned in in the format yyyymmdd.

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


回答1:


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

And if you want to retrieve the date in a custom format you just throw in some format strings.

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

As for your conversion you may use bash substring extraction (assuming you use bash of course). This also assumes that your input is consistent and "safe".

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/




回答2:


I like Tcl for date arithmetic, even though it's clunky for shell one-liners. 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)



回答3:


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

Retrieving a date relative to current time

date -v -1d

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

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



回答4:


date -d "yesterday"



来源:https://stackoverflow.com/questions/1425295/how-can-i-calculate-the-date-preceding-a-given-date-in-unix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!