How to get previous month and previous year in MonthYear format (December2020) using Linux


I want the previous month & previous year in the format: "December2020".

But while executing the below Linux command I’m getting July2020.

echo `date -d "2021-01-08" '+%B' -d 'last month'``date -d '1 year ago' +%Y

The date hardcoded parameter is in format: YYYY-MM-DD (2021-01-08)


date accepts only one -d option. In your command date -d "2021-01-08" '+%B' -d 'last month' the first -d is ignored. Only the -d "last month" applies. Because of that, and since we have August right now, the output is July.

You probably wanted to use

date -d '2021-01-08 - 1 month' +%B%Y

which prints December2020.

If you really wanted to concat the previous month and previous year together, you could use

echo "$(date -d'2021-01-08 - 1 month' +%B)$(date -d'2021-01-08 - 1 year' +%Y)"

but that would give rather strange results:

2021-01-08 → December2020 # 1 month before input date
2021-04-30 → March2020    # 13 months before input date 

Answered By – Socowi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published