Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the previous month date in asp.net

Tags:

c#

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?

like image 952
Optimus Avatar asked Feb 05 '13 07:02

Optimus


3 Answers

Try this :

DateTime d = DateTime.Now;
d = d.AddMonths(-1);
like image 109
Iswanto San Avatar answered Nov 14 '22 10:11

Iswanto San


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)

like image 26
dutzu Avatar answered Nov 14 '22 11:11

dutzu


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.

like image 44
Varinder Singh Avatar answered Nov 14 '22 11:11

Varinder Singh