Using `date` command to get previous, current and next month

前端 未结 4 968
感情败类
感情败类 2020-12-02 09:03

I am using below to get previous, current and the next month under Ubuntu 11.04:

LAST_MONTH=`date +\'%m\' -d \'last month\'`
NEXT_MONTH=`date +\         


        
4条回答
  •  既然无缘
    2020-12-02 09:49

    the following will do:

    date -d "$(date +%Y-%m-1) -1 month" +%-m
    date -d "$(date +%Y-%m-1) 0 month" +%-m
    date -d "$(date +%Y-%m-1) 1 month" +%-m
    

    or as you need:

    LAST_MONTH=`date -d "$(date +%Y-%m-1) -1 month" +%-m`
    NEXT_MONTH=`date -d "$(date +%Y-%m-1) 1 month" +%-m`
    THIS_MONTH=`date -d "$(date +%Y-%m-1) 0 month" +%-m`
    

    you asked for output like 9,10,11, so I used the %-m

    %m (without -) will produce output like 09,... (leading zero)

    this also works for more/less than 12 months:

    date -d "$(date +%Y-%m-1) -13 month" +%-m
    

    just try

    date -d "$(date +%Y-%m-1) -13 month"
    

    to see full result

提交回复
热议问题