Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

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

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 +'%m' -d 'next month'`
THIS_MONTH=`date +'%m' -d 'now'`

It works well until today, the last day of October, 2012 (2012-10-31)

I get below result as of now:

$ date
Wed Oct 31 15:35:26 PDT 2012
$ date +'%m' -d 'last month'
10
$ date +'%m' -d 'now'
10
$ $ date +'%m' -d 'next month'
12

I suppose the outputs should be 9,10,11 respectively.

Don't understand why date outputs behave like this. What should be a good way to get consistant previous, current and next month instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that date takes your request quite literally and tries to use a date of 31st September (being 31st October minus one month) and then because that doesn't exist it moves to the next day which does. The date documentation (from info date) has the following advice:

The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:

 $ date -R
 Thu, 31 Jul 2003 13:02:39 -0700
 $ date --date='-1 month' +'Last month was %B?'
 Last month was July?
 $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
 Last month was June!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...