- 1 month
will subtract one from the month number, and then if the resulting date is not valid (February 30
, for example), adjust it so that it is valid. So December 31 - 1 month
is December 1
, not a day in November, and March 31 - 1 month
is March 3
(unless executed in a leap year).
Here's quote from the info page for Gnu date
(which is the date
version which implements this syntax), which includes a good suggestion to make the arithmetic more robust:
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!
Another warning, also quoted from the info page:
Also, take care when manipulating dates around clock changes such as
daylight saving leaps. In a few cases these have added or subtracted
as much as 24 hours from the clock, so it is often wise to adopt
universal time by setting the TZ
environment variable to UTC0
before embarking on calendrical calculations.
Best Answer
You can use the
date(1)
command.For example: