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?
Start with the current date ( date ) -> 2017-03-06. Set that date to the 1st day of its month ( -v1d ) -> 2017-03-01. Subtract one day from that ( -v-1d) -> 2017-02-28. Format the date ( +%d%b%Y ) -> 28Feb2017.
These are the most common formatting characters for the date command: %D – Display date as mm/dd/yy. %Y – Year (e.g., 2020) %m – Month (01-12)
In modern versions of Windows, the date command accepts a four-digit date, e.g., MM-DD-YYYY. With the /t switch, the date command displays the system date, without prompting for a new one.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With