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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try this :

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

Method 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)

Method 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.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x