How to get the previous month date in asp.net

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)


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.


Try this :

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

Tags:

C#

Asp.Net