How to get previous month’s month and year?

The code I am using to get the previous month but same year is:

now.AddMonths(-1).ToString(“yyyy-MM”)

How do I also get the previous year?

Currently it is January 2022 and I want it to be December 2021.

Thank you!

Hi @maria.mitova

Try out this ayntax

Now.AddMonths(-1).ToString("MMM")+" "+Now.AddYears(-1).ToString("yyyy")

Thanks
Robin

Thanks, @Robinnavinraj_S , this one worked!

This is incorrect. It will ALWAYS get the last year. So in February it will return Jan 2021. Pretty sure he just wants the month and year from the previous month, so it would be…

Now.AddMonths(-1).ToString(“MMM yyyy”)

…this month that will give you December 2021. Next month it’ll give you January 2022.

The one you marked as the solution is incorrect. In February it will return “January 2021” but I think you want “January 2022” since you said you want the previous month’s month and year, not the previous month and previous year.

Here is the code for previous month’s month and year.

Now.AddMonths(-1).ToString(“MMM yyyy”)

Hi @postwick

Have a look at her expected output so that only i ill gave solution like this

But you have to think beyond that. In February do they want January 2021 or January 2022? The title says “previous month’s month and year.” In February, the previous month’s month and year is January 2022 not January 2021.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.