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

前端 未结 4 1565
执笔经年
执笔经年 2021-01-21 16:30

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

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-21 17:09

    ~$ 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/

提交回复
热议问题