How to get the previous month date in asp.net

I need to get the previous months date in asp.net which means that if the current date is 5/2/2013 then I want to display the previous date as 5/1/2013. How to solve this?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Try this :

DateTime d = DateTime.Now;
d = d.AddMonths(-1);

Solution 2

The solution is to substract 1 month:

DateTime.Now.AddMonths(-1)

Or if not just build the datetime object from scratch:

var previousDate = DateTime.Now.AddMonth(-1);

var date = new DateTime(previousDate.Year, previousDate.Month, DateTime.Now.Day);

this time you are guaranteed that the year and month are correct and the day stays the same. (although this is not a safe algorithm due to cases like the 30th of march and the previous date should be 28/29th of February, so better go with the first sugeestion of substracting a month)

Solution 3

If you already have date time in string format

var strDate = "5/1/2013";
var dateTime = DateTime.ParseExact(strDate, 
                                   "dd/MM/yyyy",
                                   CultureInfo.InvariantCulture);

var lastMonthDateTime = dateTime.AddMonths(-1);

else if you have DateTime object just call it’s AddMonths(-1) method.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply