'1 month ago' gives unexpected results when the previous month has fewer days than the current month.
For March 1-28 '1 month ago' is February but
for March 29-31 '1 month ago' is March.
Using GNU coreutils date:-
Code:
for day in 2013-03-28 2013-03-29 2013-03-30 2013-03-31 2013-04-01
do
month_ago=$(date '+%e %b' -d "$day 1 month ago")
echo "1 month ago on $day is $month_ago"
done
1 month ago on 2013-03-28 is 28 Feb # As expected
1 month ago on 2013-03-29 is 1 Mar # There isn't a 29 Feb
1 month ago on 2013-03-30 is 2 Mar # There isn't a 30 Feb
1 month ago on 2013-03-31 is 3 Mar # There isn't a 31 Feb
1 month ago on 2013-04-01 is 1 Mar # As expected
A work-around is to calculate the previous month from first day of the current month instead of from today.
Code:
first_day=$(date '+%Y-%m-01') # e.g. "2013-04-01"
last_month=$(date '+%m' -d "$first_day 1 month ago") # e.g. "03"
However the 'Output'/'Correct Result' stated in post #1 are the wrong way round for this to be the cause of the original poster's problem.
Quote:
Output:
02
Correct Result:
03
|